使用创建的 SQL Server 表构建简单的 .NET Web 应用程序。我不断收到有关 SqlDataReader 的错误,并且被困在哪里出错了。
这是我的错误:附加信息:关键字“表”附近的语法不正确。
这是我的代码:
编辑:
bool authenticated = AuthenticateMe(txtUsername.Text, txtPassword.Text);
if (authenticated)
{
Response.Redirect("Home.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
private bool AuthenticateMe(string username, string password)
{
// string ErrorMessage = "";
string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
string commandText = "SELECT Username from [Table] where Username = @name AND Password = @pwd";
// try
// {
using (SqlConnection sqlConnection1 = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, sqlConnection1))
{
sqlConnection1.Open();
cmd.Parameters.AddWithValue("@name", username);
cmd.Parameters.AddWithValue("@pwd", password);
int result = (int)cmd.ExecuteNonQuery();
if (result > 0)
{
return true;
}
else
{
return false;
}
}
}
第一版(编辑前):
protected void bnLogin_Click(object sender, EventArgs e)
{
bool authenticated = AuthenticateMe(txtUsername.Text, txtPassword.Text);
if (authenticated)
{
Response.Redirect("Home.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
private bool AuthenticateMe(string userName, string password)
{
string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
sqlConnection1.Open();
SqlCommand cmd = new SqlCommand("SELECT Username from Table where Username = userName");
cmd.Connection = sqlConnection1;
SqlDataReader reader = cmd.ExecuteReader();
Response.Write("Entered Sucessfully");
reader = cmd.ExecuteReader();
string localUserName = (string)reader["Username"];
sqlConnection1.Close();
if (userName.Equals(localUserName))
{
return true;
}
else
{
return false;
}