gpt4 book ai didi

c# - SqlParameter 的正确语法

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:55 28 4
gpt4 key购买 nike

我正在尝试转换:

command.Parameters.Add (new SqliteParameter (DbType.Int32) { Value = id });

到一个普通的 SqlParameter :

command.Parameters.Add(new SqlParameter(DbType.Int32) { Value = id });

除了这一行,我现在已经设法转换了每一行,但我遇到了这些错误:

Error   3   Argument 1: cannot convert from 'System.Data.DbType' to 'object[]'
Error 2 The best overloaded method match for 'System.Data.SqlClient.SqlParameter.SqlParameter(object[])' has some invalid arguments

完整功能代码:

public User GetUser(int id)
{
var u = new User();
lock (locker)
{
connection = new SqlConnection("Data Source=" + path + ";Initial Catalog=DB;User ID=sa;Password=***********th");
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Select * from tblUsers WHERE UserID = ?";
command.Parameters.Add(new SqlParameter(DbType.Int32) { Value = id });
var r = command.ExecuteReader();
while (r.Read())
{
u = FromReader(r);
break;
}
}
connection.Close();
}
return u;
}

最佳答案

我觉得你在看这个;

command.Parameters.Add(new SqlParameter("@YourParameterName", SqlDbType.Int32).Value = id;

编辑您的问题后;

您可以使用 AddWithValue方法。 Add(String, Object) method已经过时了。喜欢;

command.CommandText = "Select * from tblUsers WHERE UserID = @id";
command.Parameters.AddWithValue("@id", id);

如果您使用 SQL Server 作为数据库,您应该命名您的参数,将其添加到具有相同名称的 AddWithValue

当您使用 OleDbCommand 时,参数的顺序很重要。因为作为MSDN说:

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:

SELECT * FROM Customers WHERE CustomerID = ?

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

关于c# - SqlParameter 的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20870628/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com