插入到 Access 数据库不会提交



我有这个简单的代码:

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时,我看到什么也没发生。

可能是什么问题?

试试这个。始终使用参数化查询。SQL 插入文本不使用参数。这是错误SQL注入的原因

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

完成查询后,不要在查询中使用;更新此

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

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

 try
        {
            using (var connection1 = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=mydb.mdb"))
            {
                connection1.Open();
                OleDbCommand cmd = new OleDbCommand();
                Int32 count = 0; // (Int32)cmd.ExecuteScalar();
                string Query = "select count(*) from Stand where Number='" + comboBox1.Text + "'";
                using (cmd = new OleDbCommand(Query, connection1))
                {
                    cmd.CommandType = CommandType.Text;
                    count = (Int32)cmd.ExecuteScalar();
                }
                if (count == 1)
                {
                    label1.Text = comboBox1.Text + " is Already Exist!";
                }
                else
                {
                    using (cmd = new OleDbCommand("insert into Stand ([Number]) values (@Value)", connection1))
                    {
                        //cmd.Connection = connection1;
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@Value", 3);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }
        catch (Exception ex)
        {
        } 

最新更新