我编写了一些代码来将标签文本属性更改为数据库中的值。但是我遇到了问题。代码如下:
OleDbConnection Con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\attDB.accdb");
try
{
Con.Open();
string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID="+tID.Text+" && t_pass="+tPass.Text;
OleDbCommand cmd = new OleDbCommand(strcom1,Con);
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (reader.HasRows)
{
if (reader.Read())
{
t_Name.Visible = true;
t_Name.Text = reader["t_Name"].ToString();
}
}
else
{
t_Name.Text = "";
}
reader.Close();
Con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex);
}
finally
{
Con.Close();
}
答案 0 :(得分:2)
我认为你的查询字符串是错误的。 AND运算符
string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID="+tID.Text+" AND t_pass="+tPass.Text;
^^^
但是正确引用字符串参数也存在问题。您应该避免字符串连接并构建像这样的参数化查询
string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID=? AND t_pass=?";
OleDbCommand cmd = new OleDbCommand(strcom1,Con);
cmd.Parameters.AddWithValue("@p1", Convert.ToInt32(tID.Text);
cmd.Parameters.AddWithValue("@p2", tPass.Text);
正如您所看到的,现在您的查询文本更具可读性,并且不再需要在文本列的值周围添加引号,因为这项工作被传递给比您和我更了解的框架代码如何格式化特定数据类型。当然,Sql Injection
没有更多的空间答案 1 :(得分:1)
你的SQL看起来不对劲。假设你的字段t_ID和t_pass都是字符串,你还需要用引号括起来:
string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID=\""+tID.Text+"\" AND t_pass=\""+tPass.Text + "\"";
将查询打开到SQL注入时,连接查询也不是一个好主意。最好使用SQL参数。我知道你是一个初学者,但很快就要好好学习这个;)