1

我需要向 SQL Server 数据库表中添加一个文本框值。下面是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
    SqlConnection con = new SqlConnection(str);
    string qry = "insert into SubjectMaster (SubjectName) values (@TxtSubjectName)";
    con.Open();
    SqlCommand cmd = new SqlCommand(qry, con);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@TxtSubjectName", TxtSubjectName.Text);
    cmd.ExecuteNonQuery();
    MessageBox.Show("Added Successfully!!");
    con.Close();
}

但是,数据不应该添加到表中...请帮助我...感谢您的帮助...

4

3 回答 3

0

如果它有效,请先尝试调试您的查询,我认为您与数据库的连接不起作用。

string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";

应该有这个'。数据源后Data Source=.\\SQLEXPRESS

于 2013-02-27T12:01:55.457 回答
0

试试这个,告诉我消息信息内容是什么

private void button1_Click(object sender, EventArgs e)
{
    string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
    using( SqlConnection con = new SqlConnection(str)){
                            try{
                                con.Open();
                                string qry = "insert into SubjectMaster (SubjectName) values (@TxtSubjectName)";
                                SqlCommand cmd = new SqlCommand(qry, con);
                                cmd.CommandType = CommandType.Text;
                                cmd.Parameters.AddWithValue("@TxtSubjectName", TxtSubjectName.Text);
                                cmd.ExecuteNonQuery();
                                MessageBox.Show("Added Successfully!!");
                               }
                          catch{
                                MessageBox.Show("connection is failed!!");
                               }
                                                       }
}
于 2014-08-07T10:16:38.437 回答
-1

尝试这个

     SqlConnection con = new SqlConnection(@"Data Source=SL-20\SQLEXPRESS;Initial   Catalog=TestDB;User ID=sa;Password=sl123;");
        string query = " insert into name(name)values('" + TextboxTest.Text + "')";
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();
        con.Close();
于 2014-08-07T10:08:01.627 回答