gpt4 book ai didi

c# - 带参数的 ASP.NET ODBC 查询

转载 作者:太空狗 更新时间:2023-10-29 19:49:32 30 4
gpt4 key购买 nike

请帮帮我,我不知道下面的代码有什么问题:

        OdbcConnection conn = new OdbcConnection(connString);
String query = "INSERT INTO customer (custId, custName, custPass, "+
"custEmail, custAddress, custAge) VALUES (" +
"@ID, @Name, @Pass, @Email, @Address, @Age)";

OdbcCommand exe = new OdbcCommand(query, conn);
exe.Parameters.Add("@ID", OdbcType.UniqueIdentifier).Value = id;
exe.Parameters.Add("@Name", OdbcType.VarChar).Value = name;
exe.Parameters.Add("@Pass", OdbcType.VarChar).Value = pass;
exe.Parameters.Add("@Email", OdbcType.VarChar).Value = email;
exe.Parameters.Add("@Address", OdbcType.VarChar).Value = address;
exe.Parameters.Add("@Age", OdbcType.Int).Value = age;
conn.Open();
exe.ExecuteNonQuery(); // ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 6.

当我尝试执行查询时,此代码向我抛出 Too few parameters. 错误。数据库很好,当我将值硬编码到查询中而不是使用参数时,它工作正常。

谢谢。

最佳答案

来自 MSDN:

When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder. For example:

SELECT * FROM Customers WHERE CustomerID = ?

将您的查询重写为

OdbcConnection conn = new OdbcConnection(connString);
String query = "INSERT INTO customer (custId, custName, custPass, "+
"custEmail, custAddress, custAge) VALUES (" +
"?, ?, ?, ?, ?, ?)";

参数计数的顺序!

编辑:可以这样添加参数:

OdbcCommand exe = new OdbcCommand(query, conn);
exe.Parameters.Add("ID", OdbcType.UniqueIdentifier).Value = id;
exe.Parameters.Add("Name", OdbcType.VarChar).Value = name;
exe.Parameters.Add("Pass", OdbcType.VarChar).Value = pass;
exe.Parameters.Add("Email", OdbcType.VarChar).Value = email;
exe.Parameters.Add("Address", OdbcType.VarChar).Value = address;
exe.Parameters.Add("Age", OdbcType.Int).Value = age;

关于c# - 带参数的 ASP.NET ODBC 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1535994/

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