繁体   English   中英

C#中的数据库访问

[英]Database access in c#

我正在尝试使用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()rdr1.executereader()运行时错误。 我在其他地方也可以使用它的连接数据库

这是非常快速和可怕的不安全行为:

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

暂无
暂无

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

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