插入Access数据库不会提交

时间:2016-03-09 11:47:56

标签: c# oledb

我有这个简单的代码:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        OleDbConnection myConnection = new OleDbConnection();
        myConnection.ConnectionString = myConnectionString;
        myConnection.Open();


        OleDbCommand cmd = myConnection.CreateCommand();
        cmd.CommandText = "select count(*) from Stand where Number='" + comboBox1.Text + "'";
        Int32 count = (Int32)cmd.ExecuteScalar();
        myConnection.Close();
        if (count == 1)
        {
            label1.Text = comboBox1.Text + " is Already Exist!";
        }
        else
        {
            myConnection.Open();
            OleDbCommand cmd2 = new OleDbCommand("insert into Stand ([Number]) values (3);",myConnection);
            cmd2.ExecuteNonQuery();
            label1.Text = comboBox1.Text + " Added";
            myConnection.Close();
        }
    }

返回"已添加" (应该可以使用!),但是当我打开mydb.mdb时,我发现没有任何反复发生。

可能是什么问题?

2 个答案:

答案 0 :(得分:2)

试试这个。总是使用参数化查询。你的sql插入文本不使用参数。 这是导致错误 SqlInjection

的原因
 myConnection.Open();
    OleDbCommand cmd2 = new OleDbCommand("insert into Stand ([Number]) values(@test)",myConnection);
    cmd.Parameters.AddWithValue("@test", 3);
    cmd2.ExecuteNonQuery();

答案 1 :(得分:1)

完成查询后,请勿在查询中使用@Override protected void onProgressUpdate(String... pro) { testdialog.setMessage(pro[0]); } 更新此

;

或改变整个逻辑尝试这个..

myConnection.Open();
OleDbCommand cmd2 = new OleDbCommand("insert into Stand ([Number]) values (3)",myConnection);