简体   繁体   English

添加参数到DbCommand的例外情况

[英]Exception in Add Parameter To DbCommand

I need an update command with parameters, and for some reasons I can't use stored procedures, actually we generate update command depend on database, table and columns, the following forms are we use: 我需要一个带参数的更新命令,由于某些原因我无法使用存储过程,实际上我们根据数据库,表和列生成更新命令,我们使用以下表格:

        string conStr = "Provider=SQLNCLI10;Server=.\\sql2008;DataBase=MyDataBase;Trusted_Connection=true;";

        DbProviderFactory dbFactory = DbProviderFactories.GetFactory("System.Data.OleDb");
        DbConnection dbConnection = dbFactory.CreateConnection();
        dbConnection.ConnectionString = conStr;

        DbCommand dbCommand = dbFactory.CreateCommand();
        dbCommand.CommandText = "UPDATE [Student] SET Name = @Name Where Id = @Id";

        DbParameter param1 = dbCommand.CreateParameter();
        param1.ParameterName = "@Name";
        param1.Value = "LOL";
        DbParameter param2 = dbCommand.CreateParameter();
        param2.ParameterName = "@Id";
        param2.Value = 5;

        dbCommand.Parameters.Add(param1);
        dbCommand.Parameters.Add(param2);

        dbConnection.Open();
        dbCommand.ExecuteNonQuery();
        dbConnection.Close();

But there is an exception: 但有一个例外:

Must declare the scalar variable "@Name" 必须声明标量变量“@Name”

Where is the problem in this code? 这段代码中的问题在哪里? Does anyone have an idea about this? 有没有人对此有所了解?

As you are using System.Data.OleDb as database provider ( regardless you are using a sql server ) you need to use the ? 当您使用System.Data.OleDb作为数据库提供程序时(无论您使用的是SQL服务器),您需要使用? as the parameter placeholder like: 作为参数占位符,如:

"UPDATE [Student] SET Name = ? Where Id = ?";

By using the System.Data.OleDb provider the names of the parameters doesn`t matter anymore but you need to ensure that the occurance of the parameters match the order the parameterobjects are added to the command objects parameter collection. 通过使用System.Data.OleDb提供程序,参数的名称不再重要,但您需要确保参数的出现与参数对象添加到命令对象参数集合的顺序相匹配。

EDIT: If you want to keep the @ as parameter placeholder you can just change this: 编辑:如果你想保留@ as参数占位符,你可以改变这个:

DbProviderFactory dbFactory = DbProviderFactories.GetFactory("System.Data.OleDb");

to

DbProviderFactory dbFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");

Try that and let me know if it works. 尝试一下,让我知道它是否有效。

DbParameter param1 = dbCommand.CreateParameter();
param1.ParameterName.AddWithValue("@Name", Textbox1.Text);

or 要么

DbParameter param1 = dbCommand.CreateParameter();
param1.SelectCommand.Parameters.AddWithValue("@Name", Textbox1.Text);
command.CommandText = "EXEC [dbo].[PR_GetPurchase_ProjectBUDetails] " + prjID.ToString()+ " ," + empID.ToString();

Hard code parameters while calling stored procedure . 调用stored procedure硬代码参数。
This solved my issue. 这解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM