OleDb使用参数值更新sql不会更新Access中的记录 [英] OleDb Update sql with Parameter value not updating record in Access

查看:133
本文介绍了OleDb使用参数值更新sql不会更新Access中的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以在下面的代码中分辨出什么地方吗?

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显示0条记录,实际上它没有更新可用的记录.

MessageBox shows 0 records and it is actually not updating the record which is available.

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

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

推荐答案

首先,OleDbParameter是定位的,未命名.阅读文档中的备注部分. .忽略任何无法理解的答案.

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:

第二,编写代码:

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

结果:

这篇关于OleDb使用参数值更新sql不会更新Access中的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆