运行此代码时出错,帮我解决此错误。 ' ='附近的语法不正确。
我的问题是这是什么样的错误。?
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;
}
}
}
}
答案 0 :(得分:3)
考虑一下您正在创建的字符串。假设txtStudentID.Text
是字符串Joe
。您正在创建Select * from tblStudents where ID = Joe
,这显然是不正确的。 Joe
需要引用它。
但是 ,不要只是在它周围加上引号。 Here's why:
正确的做法是使用参数化语句,如上面链接的网站here所述。将他们的示例应用于您的代码,我们会得到类似的结果:
SqlCommand sqlQuery = new SqlCommand("Select * from tblStudents where ID = @username", con);
sqlQuery.Parameters.AddWithValue("@username", txtStudentID.Text);
...但我不知道你的ViewState
是什么,所以无法帮助你在那里应用。
答案 1 :(得分:1)
使用用户输入文本的SQL命令几乎总是使用参数化查询来避免SQL注入攻击和语法错误,并且养成在using
中包装一次性对象(如数据库连接)的习惯也很好语句:
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");
}
}
答案 2 :(得分:0)
这里有几件事。
在这种情况下,应始终使用SQL参数。
此外,学生ID是数据库中的文本字段还是数字?
如果是数字,那么文本框在哪里被初始化? page_load是最先发生的事情之一,因为你在所有page_loads上运行它(即使是第一次),如果它是一个空字符串,无论你是否使用参数,它都会崩溃,因为空字符串无法转换为数字。