连接已打开

时间:2014-02-23 13:53:23

标签: c# sql

几个月前,我为一个项目做了一个测试程序,一切都很好。 现在我正在研究程序本身,所以我从测试程序中复制了代码 更改了列,按钮等的名称,因此它适合当前程序。 当我尝试在数据库中添加内容时,它在第一次单击时没有任何作用 第二个弹出错误,表示连接已打开..我真的不知道是什么 问题。我试图再次检查我是否在列名或数据库名称中出错 但一切似乎都是正确的。 注意:我还有一个显示数据库数据的函数,它没有任何问题。

private void InsertData()
{
    string NewCode = GenerateCode();
    string NewSentence = txtSentence.Text;
    string NewRow = NewRowNum();
    try
    {
        string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (@NewBinaryString,@NewSentence,@NewRowNumber)";
        SqlCommand DataAdd = new SqlCommand(AddData, Connection);
        DataAdd.Parameters.AddWithValue("@NewBinaryString", NewCode);
        DataAdd.Parameters.AddWithValue("@NewNewSentence", NewSentence);
        DataAdd.Parameters.AddWithValue("@NewRowNumber", NewRow);
        Connection.Open();
        DataAdd.ExecuteNonQuery();
        Connection.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}
//Checking the banary code in the last row
string GenerateCode()
{
    string RowNo = RowFind();
    int Row = int.Parse(RowNo);
    int Code = Row + 1;
    string Cd = Convert.ToString(Code, 2);
    int Ln = Cd.Trim().Length;
    if (Ln == 3)
    {
        Cd = "100" + Cd;
    }
    else if (Ln == 4)
    {
        Cd = "10" + Cd;
    }
    else if (Ln == 5)
    {
        Cd = "1" + Cd;
    }
    return Cd;
}
//Finding the last row
string RowFind()
{
    Connection.Open();
    string queryString = string.Format("SELECT * FROM ShopSentences");
    SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
    DataTable dt = new DataTable("ShopSentences");
    sda.Fill(dt);
    Connection.Close();
    return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
    string Row = RowFind();
    int CalcRow = int.Parse(Row) + 1;
    Row = CalcRow.ToString();
    return Row;
}

看似打开的连接是字符串RowFind()中的连接。

以下是数据库的其他相关内容:

public partial class frmShop : Form
{
    System.Data.SqlClient.SqlConnection Connection;

    public frmShop()
    {
        string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
        Connection = new System.Data.SqlClient.SqlConnection();
        Connection.ConnectionString = DatabaseConnection;
        InitializeComponent();
    }

    private void frmShop_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
        this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);

    }

    private void GetSentence()
    {
        try
        {
            Connection.Open();
            SqlDataReader ReadSentence = null;
            Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
            string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = @BinaryString";
            SqlCommand Command = new SqlCommand(CommandString, Connection);
            Command.Parameters.Add("@BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
            ReadSentence = Command.ExecuteReader();
            while (ReadSentence.Read())
            {
                txtSentence.Text = (ReadSentence["Sentence"].ToString());
                Fit = 1;
            }
            Connection.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

3 个答案:

答案 0 :(得分:1)

由于您多次重复使用相同的连接Connection.Open();,因此收到错误。

您的方法InsertData()使用相同的方法执行此操作3次。

您应该创建连接对象的新实例并将其置于您的方法上。

使用Statement是可行的方法。


private void InsertData()
{
    using (var Connection = new SqlConnection(DatabaseConnection))
    {
        string NewCode = GenerateCode();
        string NewSentence = txtSentence.Text;
        string NewRow = NewRowNum();
        try
        {
            Connection.Open();
            string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (@NewBinaryString,@NewSentence,@NewRowNumber)";
            SqlCommand DataAdd = new SqlCommand(AddData, Connection);
            DataAdd.Parameters.AddWithValue("@NewBinaryString", NewCode);
            DataAdd.Parameters.AddWithValue("@NewNewSentence", NewSentence);
            DataAdd.Parameters.AddWithValue("@NewRowNumber", NewRow);
            DataAdd.ExecuteNonQuery();
            //Connection.Close(); no need to close
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

如果存储RowFind()

返回的行,则可以再保存一个连接
string RowFind()
{
    using (var Connection = new SqlConnection(DatabaseConnection))
    {  
        Connection.Open();
        string queryString = string.Format("SELECT * FROM ShopSentences");
        SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
        DataTable dt = new DataTable("ShopSentences");
        sda.Fill(dt);
        //Connection.Close();
        return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
    }
}

所以你要连接一次而不是两次:

var Row  = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;

将属性的连接字符串变量声明为属性,以便重用它:

private string DatabaseConnection {get; set;}

答案 1 :(得分:0)

相反,使用实例级别的SqlConnection,您应该只提供一个用于创建连接的公共工厂:

public partial class frmShop : Form
{
    private string ConnectionString
    {
        get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
    }

    public frmShop()
    {
        InitializeComponent();
    }

    private SqlConnection CreateConnection()
    {
        var conn = new SqlConnection(ConnectionString);
        conn.Open();
        return conn;
    }

    private void frmShop_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
        this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
    }
    private void GetSentence()
    {
        try
        {
            using (var conn = CreateConnection())
            {
                var BinaryInt = int.Parse(txtBinaryString.Text);
                var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = @BinaryString";
                using (var Command = new SqlCommand(commandString, conn))
                {
                    Command.Parameters.Add("@BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;

                    using (var readSentence = Command.ExecuteReader())
                    {
                        while (readSentence.Read())
                        {
                            txtSentence.Text = (readSentence["Sentence"].ToString());
                            Fit = 1;
                        }
                    }
                }
            }
         }

        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void InsertData()
    {
        try
        {
            using (var conn = CreateConnection())
            {
                var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (@NewBinaryString,@NewSentence,@NewRowNumber)";
                using (var comm = new SqlCommand(commandString, conn))
                {
                    comm.Parameters.AddWithValue("@NewBinaryString", GenerateCode());
                    comm.Parameters.AddWithValue("@NewNewSentence", txtSentence.Text);
                    comm.Parameters.AddWithValue("@NewRowNumber", NewRowNum());

                    comm.ExecuteNonQuery();
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
    //Checking the banary code in the last row
    string GenerateCode()
    {
        string RowNo = RowFind();
        int Row = int.Parse(RowNo);
        int Code = Row + 1;
        string Cd = Convert.ToString(Code, 2);
        int Ln = Cd.Trim().Length;
        if (Ln == 3)
        {
            Cd = "100" + Cd;
        }
        else if (Ln == 4)
        {
            Cd = "10" + Cd;
        }
        else if (Ln == 5)
        {
            Cd = "1" + Cd;
        }
        return Cd;
    }
    //Finding the last row
    string RowFind()
    {
        using (var conn = CreateConnection())
        {
            var commandString = "SELECT * FROM ShopSentences";
            using (var comm = new SqlCommand(commandString, conn))
            {
                using (var sda = new SqlDataAdapter(queryString, Connection))
                {
                    using (DataTable dt = new DataTable("ShopSentences"))
                    {
                        sda.Fill(dt);
                        return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
                    }
                }
            }
        }
    }

    string NewRowNum()
    {
        var Row = RowFind();
        var CalcRow = int.Parse(Row) + 1;
        return CalcRow.ToString();


}
}

但这只是一个开始,你不应该在你的Form类中有任何硬SQL依赖。

答案 2 :(得分:0)

在代码中多次共享同一个SqlConnection实例时,不是直接打开,而是先检查连接状态,然后再打开它(如果尚未打开)。例如:

if(Connection.State!= ConnectionState.Open)
       Connection.Open();