我正在尝试创建一个登录页面,我从SQL Server数据库中获取密码和电子邮件。我想比较密码和电子邮件。
private void buttoninloggen_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionstring))
{
connection.Open();
string emailinlog = textBoxEmailLogin.Text;
string passwordinlog = textBoxPasswordLogin.Text;
string vergelijken = "select * from Account where Email = @email and Password = @password";
SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);
MessageBox.Show("tot hier is t goed");
using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
{
ophalen.Parameters.AddWithValue("@email", emailinlog);
ophalen.Parameters.AddWithValue("@password", passwordinlog);
DataTable tafel = new DataTable();
adapter.Fill(tafel);
if (tafel.Rows.Count > 0)
{
MessageBox.Show("ingelogd");
}
}
}
}
我收到此错误消息:
System.Data.SqlClient.SqlException:'必须声明标量变量“@email”。'
我做错了什么?
答案 0 :(得分:1)
你的代码错了。您可以使用查询和连接定义SqlDataAdapter
,但在尝试使用它填充DataTable
之前,不要对其执行任何其他操作。它不知道@email
或@password
的值是什么,因为你永远不会告诉它。
您的代码应如下所示:
private void buttoninloggen_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionstring))
{
connection.Open();
string emailinlog = textBoxEmailLogin.Text;
string passwordinlog = textBoxPasswordLogin.Text;
string vergelijken = "select * from Account where Email = @email and Password = @password";
// Moved the 'SqlDataAdapter' further down
// SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);
MessageBox.Show("tot hier is t goed");
using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
{
ophalen.Parameters.AddWithValue("@email", emailinlog);
ophalen.Parameters.AddWithValue("@password", passwordinlog);
DataTable tafel = new DataTable();
// SqlDataAdapter is now here
// As it has been passed the SqlCommand it understands the parameters
// Wrapped in using statement for disposal
using (SqlDataAdapter adapter = new SqlDataAdapter(ophalen))
{
adapter.Fill(tafel);
if (tafel.Rows.Count > 0)
{
MessageBox.Show("ingelogd");
}
}
}
}
}
答案 1 :(得分:-1)
考虑将语法更改为我的程序中的工作代码:
ophalen.Parameters.Add(new SqlParameter("@email", emailinlog));