简体   繁体   English

C#中的数据库访问

[英]Database access in c#

I am trying to access database in c# but i am getting runtime error.code is below 我正在尝试使用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();
}

I'm getting a runtime error in rdr1.executereader() . 我在rdr1.executereader()rdr1.executereader()运行时错误。 I'm using it connection database at other places also where it is working fine 我在其他地方也可以使用它的连接数据库

This is the VERY QUICK AND HORRIBLY UNSAFE HACK: 这是非常快速和可怕的不安全行为:

The variable admission_no is a string. 变量admission_no是一个字符串。 You need to to enclose it in quotes. 你需要把它们放在引号。

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

However this approach leaves you wide open to SQL Injection attacks which is a massive risk. 但是,这种方法使您很容易受到SQL注入攻击的威胁,这是一个巨大的风险。

A MUCH better approach (I can't stress this strongly enough) is to set your query string to 一个更好的方法(我对此不太强调)是将查询字符串设置为

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

and then add the parameter to the command: 然后将参数添加到命令中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM