c#中的数据库访问

本文关键字:访问 数据库 | 更新日期: 2023-09-27 18:11:37

我试图在c#中访问数据库,但我得到运行时错误。代码在

下面
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()中得到一个运行时错误。我使用它连接数据库在其他地方也工作良好

c#中的数据库访问

这是一个非常快速和非常不安全的HACK:

变量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();