Asp.net “=”附近的语法不正确
当我运行此代码时,它会给出一个错误,请帮助我解决此错误。 “=”附近的语法不正确 我的问题是这是什么样的错误Asp.net “=”附近的语法不正确,asp.net,sql-server,Asp.net,Sql Server,当我运行此代码时,它会给出一个错误,请帮助我解决此错误。 “=”附近的语法不正确 我的问题是这是什么样的错误 namespace SqlCommandBuilders { public partial class WebForm1: System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { String CS = Configura
namespace SqlCommandBuilders
{
public partial class WebForm1: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
string sqlQuery = "Select * from tblStudents where ID = "+txtStudentID.Text;
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds, "Students");
ViewState["SQL_QUERY"] = sqlQuery;
ViewState["DATASET"] = ds;
if(ds.Tables["Students"].Rows.Count > 0)
{
DataRow dr = ds.Tables["Students"].Rows[0];
txtStudentID.Text = dr["Name"].ToString();
txtTotalMarks.Text = dr["TotalMarks"].ToString();
ddlGender.SelectedValue = dr["Gender"].ToString();
}
else
{
lblStatus.ForeColor= System.Drawing.Color.Red;
lblStatus.Text = "No Student Record with ID =" + txtStudentID.Text;
}
}
}
}
使用用户文本输入的SQL命令几乎应该始终使用参数化查询,以避免SQL注入攻击和语法错误,并且养成在使用语句时包装一次性对象(如数据库连接)的习惯也是很好的:
DataSet ds = new DataSet();
using(SqlConnection con = new SqlConnection(CS)) {
string sqlQuery = "Select * from tblStudents where ID = @studentId";
using(SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con)) {
da.SelectCommand.Parameters.Add("@studentId", SqlDbType.VarChar)
.Value = txtStudentID.Text;
da.Fill(ds, "Students");
}
}
考虑一下你正在创建的字符串。假设txtStudentID.Text是字符串Joe。您将从tblStudents创建Select*,其中ID=Joe,这显然是不正确的。乔需要引用它 但是,不要只是用引号括起来 正确的做法是使用参数化语句,如上面链接的站点所述。将他们的示例应用到您的代码中,我们会得到如下结果:
SqlCommand sqlQuery = new SqlCommand("Select * from tblStudents where ID = @username", con);
sqlQuery.Parameters.AddWithValue("@username", txtStudentID.Text);
…但我不知道您的ViewState是什么,因此无法帮助您在那里应用它。这里有几点
在这种情况下,应始终使用SQL参数
另外,学生ID是数据库中的文本字段还是数字
如果是数字,文本框在哪里初始化?页面加载是最先发生的事情之一,因为您在所有页面加载上运行此操作,即使是第一次,如果它是空字符串,无论您是否使用参数,它肯定会崩溃,因为空字符串无法转换为数字。请告诉我们错误发生在哪一行。请发布完整的错误/异常详细信息。