OleDb更新sql,参数值不更新Access中的记录

时间:2012-09-01 09:44:53

标签: c# oledb

以下代码中是否有人能说出错误?

command.Connection = ConnectionManager.GetConnection();
command.CommandText = "Update Table1 SET Replaceme = ? WHERE Searchme = ?";
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("Replaceme", "Goodman");
command.Parameters.AddWithValue("Searchme", "Anand");

command.Connection.Open();
int recordsaffected = command.ExecuteNonQuery();
MessageBox.Show("Records affected : " + recordsaffected);

MessageBox显示0条记录,实际上并没有更新可用的记录。

表名(Table1)和列名(Replaceme and Searchme)拼写正确。

2 个答案:

答案 0 :(得分:6)

首先,OleDbParameter是位置,而不是命名。阅读documentation中的备注部分。忽视任何不理解这一点的答案。

这是一个极小的工作示例。

首先,创建数据库:

enter image description here

enter image description here

其次,编写代码:

using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString;
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;";
            connectionString += "Data Source=C:\\Temp\\Database1.mdb";

            using (var connection = new OleDbConnection(connectionString))
            {
                connection.Open();

                var command = connection.CreateCommand();
                command.CommandText =
                    "UPDATE Table1 SET Replaceme = ? WHERE Searchme = ?";

                var p1 = command.CreateParameter();
                p1.Value = "Goodman";
                command.Parameters.Add(p1);

                var p2 = command.CreateParameter();
                p2.Value = "Anand";
                command.Parameters.Add(p2);

                var result = String.Format("Records affected: {0}",
                    command.ExecuteNonQuery());
                MessageBox.Show(result);
            }
        }
    }
}

结果:

enter image description here

enter image description here

答案 1 :(得分:-1)

因为你正在使用它不起作用?而不是@参数化查询。使用它,它应该工作:

Update Table1 SET Replaceme = @Replaceme WHERE Searchme = @Searchme

相关问题