OleDb Update sql with Parameter value not updating record in Access

∥☆過路亽.° 提交于 2019-11-30 19:55:24

问题


Can anybody tell what is wrong in the following code ?

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 shows 0 records and it is actually not updating the record which is available.

Table name (Table1) and Column names (Replaceme and Searchme) are correctly spelled.


回答1:


First off, OleDbParameters are positional, not named. Read the Remarks section in the documentation. Disregard any answer that does not understand this.

Here's a minimal, working example.

First, create your database:

Second, write the code:

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);
            }
        }
    }
}

Result:




回答2:


Its not working because you are using ? instead of @ for the parametrized query.

Use this and it should work:

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



来源:https://stackoverflow.com/questions/12226682/oledb-update-sql-with-parameter-value-not-updating-record-in-access

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!