SqlCommand AddWithValue
本文关键字:AddWithValue SqlCommand | 更新日期: 2023-09-27 18:20:45
SqlCommand command = new SqlCommand("SELECT * FROM users WHERE Username = ? AND Password = ?", connection);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
SqlDataReader reader = null;
reader = command.ExecuteReader();
当我运行程序时,我得到
"?"附近的语法不正确。
在这一行上:
reader = command.ExecuteReader();
谁能看出我做错了什么?
using(SqlCommand command = new SqlCommand("SELECT * FROM users WHERE Username = @Username AND Password = @Password", connection))
{
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@Password", password);
using(SqlDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
//do actual works
}
}
}
使用using
关键字进行了改进,这不是必需的,但建议使用
SqlCommand command = new SqlCommand(
"SELECT * FROM users WHERE Username = @Username AND Password = @Password",
connection);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
SqlDataReader reader = null;
reader = command.ExecuteReader();
你可能想阅读sql。
你使用的是哪个DBMS?如果您使用的是 SQL Server,则查询的语法不正确。你需要:
SqlCommand cmd =
new SqlCommand(@"select *
from users
where username = @username and password = @password");
command.Parameters.AddWithValue("@username", username);
command.Parameters.AddWithValue("@password", password);