SqlConnection为null但为什么?

时间:2017-12-16 12:46:33

标签: c# sql .net sql-server ado.net

我想连接到我的GuvenliBilgisayarim数据库。但baglanti为空 - 为什么?

我的代码是:

SqlConnection baglanti = new SqlConnection("Data Source=DILEKZ\\SQLEXPRESS;Initial Catalog=GuvenliBilgisayarim;Integrated Security=True");

private void btn_giris_Click(object sender, EventArgs e)
{
    baglanti.Open();
    SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi='" + txt_kulAdi.Text + " and kullanici_sifre=" + txt_sifre.Text +"',baglanti");
    komut.Connection = baglanti;

    SqlDataReader dr = komut.ExecuteReader();

    if (dr.Read())
    {
        Rapor rpr = new Rapor();
        rpr.Show();
    }
    else
    {
        MessageBox.Show("Kullanıcı adı veya şifre yanlış");
    }

    dr.Close();
}

1 个答案:

答案 0 :(得分:6)

您的SqlCommand Text无效。正确的是(注意引号'"):

SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi='" + txt_kulAdi.Text + "'" +
                        " and kullanici_sifre='" + txt_sifre.Text + "'",baglanti);

然而,这种字符串连接对SQL injection开放。请尝试使用parameterized queries。像这样:

SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi=@kulAdi" +
                        " and kullanici_sifre=@sifre",baglanti);
komut.Parameters.AddWithValue("@kulAdi",txt_kulAdi.Text);
komut.Parameters.AddWithValue("@sifre",txt_sifre.Text);

虽然直接指定类型并使用Value属性比AddWithValue更好:

komut.Parameters.Add("@kulAdi", SqlDbType.VarChar).Value = txt_kulAdi.Text;

Can we stop using AddWithValue() already?