无法从sql数据库中读取int值

时间:2018-02-03 18:12:44

标签: c# sql-server-2012

我在C#中尝试过这段代码,而且它无法正常工作 - 我无法获取输入ID,每次运行时,id的值都为0.

SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");        

int id;

con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";

SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();

if (read.Read())
{
    id = read.GetInt32(0);
    TM_AC_SelectId.Text = id.ToString();
}
else
{
    MessageBox.Show("Error 009 ");
}

con.Close();

1 个答案:

答案 0 :(得分:4)

您应该尝试遵循ADO.NET编程的公认最佳实践:

  • 使用参数查询 - 始终 - 无异常
  • 使用using(...) { .... }结构确保正确快速处理您的资源
  • 选择真正 那些您需要的列 - 不要只使用SELECT *的懒惰 - 指定您真正需要的列!

将您的代码更改为:

// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = @EmpName;";

// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))       
using (SqlCommand cmd = new SqlCommand(query, con))
{
    // set the parameter value
    cmd.Parameter.Add("@EmpName", SqlDbType.VarChar, 100).Value = sName;

    // open connection, execute scalar, close connection
    con.Open();
    object result = cmd.ExecuteScalar();
    con.Close();

    int id;

    if(result != null)
    {
        if (int.TryParse(result.ToString(), out id)
        {
            // do whatever when the "id" is properly found  
        }
    }
}