sqlreader读取错误的列

时间:2018-11-18 11:19:16

标签: c# sql

我正在尝试从我的人员表中获取唯一ID,但读者一直在尝试获取FirstName列并尝试进行转换。至少那是我认为正在发生的事情

dataAdapter.SelectCommand = new SqlCommand("SELECT ID FROM Persons WHERE FirstName = " + txtBoxFirst.Text.ToString() + " AND LastName = " + txtBoxLast.Text.ToString()
                                                       , sqlConnection);
            sqlConnection.Open();
            SqlDataReader read = dataAdapter.SelectCommand.ExecuteReader();

            while (read.Read())
            {
                pID = (Int32.Parse(read["ID"].ToString()));
            }
            read.Close();
            sqlConnection.Close();

错误显示为

  

System.Data.SqlClient.SqlException:“将varchar值“ First”转换为数据类型int时转换失败。”

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

首先,您在查询中遗漏了'单引号,因此您的参数将不是字符串。

所以可能像

"SELECT ID FROM Persons WHERE FirstName = '" + txtBoxFirst.Text.ToString() + "' AND LastName = '" + txtBoxLast.Text.ToString() + "'"

但是有一个大问题,比SQL-Injection多。

我建议您使用参数代替连接的SQL语句字符串。

确保参数数据类型的大小与表模式相同。

string sqlQuery =  "SELECT ID FROM Persons WHERE FirstName = @FirstName AND LastName = @LastName";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
    command.Parameters.Add("@FirstName", SqlDbType.VarChar,100).Value = txtBoxFirst.Text;
    command.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = txtBoxLast.Text;

    SqlDataReader read = dataAdapter.SelectCommand.ExecuteReader();

    while (read.Read())
    {
        pID = (Int32.Parse(read["ID"].ToString()));
    }
}