c#中的数据库访问

时间:2014-07-07 07:18:52

标签: c# sql-server

我正在尝试访问c#中的数据库,但我得到运行时error.code在

之下
public void value_assign()
{
    SqlConnection conn;
    String admission_no = adm_text.Text;
    string connectionstring = "server=AMAN;database=student;Integrated Security=True";
    string query1 = "select * from fees where Admission_no=" + admission_no;
    SqlDataReader rdr1;
    conn = new SqlConnection(connectionstring);
    conn.Open();
    SqlCommand cmd1 = new SqlCommand(query1, conn);
    rdr1 = cmd1.ExecuteReader();
    while (rdr1.Read())
    {
        prospectues_fee = (float)rdr1.GetValue(1);
        registration_fee = (float)rdr1.GetValue(2);
        admission_fee = (float)rdr1.GetValue(3);
        security_money = (float)rdr1.GetValue(4);
        misslaneous_fee = (float)rdr1.GetValue(5);
        development_fee = (float)rdr1.GetValue(6);
        transport_fair = (float)rdr1.GetValue(7);
        computer_fee = (float)rdr1.GetValue(8);
        activity = (float)rdr1.GetValue(9);
        hostel_fee = (float)rdr1.GetValue(10);
        dely_fine = (float)rdr1.GetValue(11);
        back_dues = (float)rdr1.GetValue(12);
        tution_fee = (float)rdr1.GetValue(13);
        tu_mon = rdr1.GetString(14);
        other_fee = (float)rdr1.GetValue(15);

        total = (float)rdr1.GetValue(16);
    }
    conn.Close();
}

我在rdr1.executereader()中收到运行时错误。我在其他地方使用它连接数据库也正常工作

1 个答案:

答案 0 :(得分:4)

这是非常快速且可怕的不安全事件:

变量admission_no是一个字符串。您需要将其括在引号中。

string query1 = "select * from fees where Admission_no='" + admission_no + "'";

然而,这种方法让您对SQL注入攻击持开放态度,这是一个巨大的风险。

更好的方法(我不能强调这一点)是将查询字符串设置为

string query1 = "select * from fees where Admission_no=@admission_no";

然后将参数添加到命令:

SqlCommand cmd1 = new SqlCommand(query1, conn);
cmd1.Parameters.AddWithValue("@admission_no", adm_text.Text);
rdr1 = cmd1.ExecuteReader();