Dlk*_*nng 2 .net c# sql 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();
}
Run Code Online (Sandbox Code Playgroud)
你SqlCommand的Text是无效的.正确的是(注意引号'"):
SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi='" + txt_kulAdi.Text + "'" +
" and kullanici_sifre='" + txt_sifre.Text + "'",baglanti);
Run Code Online (Sandbox Code Playgroud)
但是,这种字符串连接是为SQL注入打开的.请尝试参数化查询.像这样的东西:
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);
Run Code Online (Sandbox Code Playgroud)
虽然直接指定类型并使用Value属性比AddWithValue以下更好:
komut.Parameters.Add("@kulAdi", SqlDbType.VarChar).Value = txt_kulAdi.Text;
Run Code Online (Sandbox Code Playgroud)