【问题标题】:SqlConnection is null but why?SqlConnection 为空,但为什么呢?
【发布时间】:2017-12-16 12:46:33
【问题描述】:

我想连接到我的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();
}

【问题讨论】:

  • 您是在说,实际上是在调用NullReferenceException 时抛出Open
  • 是的,我打电话,问题解决了。非常感谢:)

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


【解决方案1】:

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

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?

【讨论】:

  • 非常感谢 :)
  • 如果这个答案解决了您的问题,那么您的标题和帖子中对问题的描述完全不准确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 2021-04-25
  • 2016-06-29
  • 2011-10-11
相关资源
最近更新 更多