"Exception Unhadled" SqlConnection 打开时出错()

"Exception Unhadled" error during SqlConnection open()

在我的程序中,我有两个文本输入字段(以 windows 形式)和一个用于 add/save 将这些值输入数据库 table 的按钮。问题是一旦我点击按钮,它不会将输入插入数据库,而是显示我在下面附加的错误图像。

我的程序有什么问题?

我的工作代码:

public partial class Form1 : Form
{
    //original Connection string is exactly the following:
    //Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf";Integrated Security=True;Connect Timeout=30
    SqlConnection conn = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf;Integrated Security = True; Connect Timeout = 30");
    public Form1()
    {
        InitializeComponent();
    }

    //Save button
    private void button1_Click(object sender, EventArgs e)
    {
        conn.Open();//error pops up here after clicking the button
        SqlCommand command = conn.CreateCommand();
        command.CommandType = CommandType.Text;
        command.CommandText = "insert into Table values('"+wordbox.Text+"','"+synonymbox.Text+"')";
        command.ExecuteNonQuery();
        conn.Close();
        MessageBox.Show("Word and Synonym added!");
    }

    private void display_Click(object sender, EventArgs e)
    {
        //implement
    }
}

错误:

数据库看起来像:


更新: 我对Using模式的修改(参考CDove的回答):

    var command = new SqlCommand();
            using (command = new SqlCommand(
                          "insert into......)
))

您需要做四件事。首先,解决这个问题:

"insert into [Table] values('"+wordbox.Text+"','"+synonymbox.Text+"')"

在 Microsoft SQL 中,如果我没记错的话,values() 插入语法要求首先显式声明列。此外,"Table" 是保留字,因此您需要将其放在方括号中才能将该字用作 table 名称。以后,请避免在您的 table 模式中使用保留字。

"insert into [Table] (word, synonym) values ('"+wordbox.Text+"','"+synonymbox.Text+"')"

其次,。而是创建参数。

"insert into [Table] (word, synonym) values (@word,@syn)"

然后

 command.Parameters.AddWithValue("@word", wordbox.Text); 
 command.Parameters.AddWithValue("@syn", synonymbox.Text);
 command.ExecuteNonQuery();

第三,不要缓存你的连接。这就是它在您的代码顶部所做的,为您留下一个您必须进行微观管理的连接:

SqlConnection conn = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf;Integrated Security = True; Connect Timeout = 30");

虽然理想情况下,您会从 web.config 或 app.config 阅读本文,但我们将使用您的硬编码字符串;只留下一个字符串。

string conn = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf;Integrated Security = True; Connect Timeout = 30";   

最后,使用 using 模式。这不仅是不那么臭的代码,而且还以隐式 try-finally 的方式包含隐式 .Close().Dispose()

private void button1_Click(object sender, EventArgs e)
{
    using(var command = new SqlCommand(
             "insert into [Table] (word, synonym) values (@word,@syn)",
              new SqlConnection(conn)
          ))
    {
       command.Connection.Open();//Since we aren't reopening an old connection, errors are less likely.    
       command.CommandType = CommandType.Text;
       command.Parameters.AddWithValue("@word", wordbox.Text); 
       command.Parameters.AddWithValue("@syn", synonymbox.Text);                   

       if(command.ExecuteNonQuery() > 0 )
           MessageBox.Show("Word and Synonym added!");
    }
}

请注意,我检查了 ExecuteNonQuery 的值。那是因为这个函数returns受影响的行数;如果计数为 0,则不添加单词和同义词。

注意:这一切都是我午休时想不出来的,所以你自己测试一下,看看它对你有什么影响。