如何在sqlserver中插入数据?

时间:2014-02-24 16:59:47

标签: c# sql sql-server

我写了下面的代码但是我没有成功地在我的数据库中插入数据。 你的建议是什么?

我的数据库名称id syn 在“syn”中我有一个名为synreplace的表,有4列(Number,word,syn,freq) 哪个号码是主键。

private void button2_Click(object sender, EventArgs e)
{
    string Word = textBox5.Text;
    string Syn = textBox6.Text;

    SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + @"\bin\Debug\syn.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

    try
    {
        myConnection.Open();
        textBox4.Text = "Well done!";
    }
    catch (SqlException ex)
    {
        textBox4.Text = "You failed!" + ex.ToString();
    }

    try
    {
        SqlCommand myCommand = new SqlCommand(@"INSERT INTO synreplace (word,syn)" + "Values ('Wgord','Shyn')", myConnection);
        myCommand.ExecuteNonQuery();
        textBox4.Text = textBox4.Text + "wow";
        myCommand.Dispose();
    }
    catch (Exception ex)
    {
         textBox4.Text = textBox4.Text + ex.ToString();
    }
}

1 个答案:

答案 0 :(得分:2)

你必须在')'和Value

之间留出空格
SqlCommand myCommand = new SqlCommand(@"INSERT INTO synreplace (word,syn) Values ('Wgord','Shyn')", myConnection);

并检查freq是否接受null

<强>更新

你在运行debug时总是创建mdf文件,然后你删除旧的mdf并创建新的mdf(在这种情况下你会丢失插入的数据)

检查您的数据是否已添加,您可以插入数据并获取mdf文件并将其附加到sqlManagment以检查插入的数据

相关问题