gpt4 book ai didi

c# - .NET 数据读取器 : SqlException was unhandled by user code

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:25 25 4
gpt4 key购买 nike

致力于使用创建的 SQL Server 表构建简单的 .NET Web 应用程序。我不断收到有关 SqlDataReader 的错误,并且一直停留在我出错的地方。

这是我的错误:附加信息:关键字“Table”附近的语法不正确。

这是我的代码:

编辑:

            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;
}

最佳答案

Table是SQL中的保留关键字。试着用方括号括起来:

SqlCommand cmd = new SqlCommand("SELECT Username from [Table] where Username = userName");

关于c# - .NET 数据读取器 : SqlException was unhandled by user code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19039411/

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