大家好我有这个代码
cmd = new SqlCommand();
cmd.Connection = baglanti;
cmd.CommandText = "(musteriadi,musterisoyadi,gsm,email,sirketadi,Adres,Notlar) VALUES('" + txtMusteriAdi.Text.Trim() + "','" + txtMusteriSoyadi.Text.Trim() + "','" + txtGsm.Text.Trim() + "','" +txtEmail.Text.Trim() + "','" +txtSirketAdi.Text.Trim() + "','" +txtAdres.Text.Trim() + "','" +txtNotlar.Text.Trim() +"');";
baglanti.Open();
cmd.ExecuteNonQuery();
baglanti.Close();
我将cmd定义为public SqlCommmand
,并且每当代码进入cmd.ExecuteNonQuery()
时,它都会落在我能做的事情上。
答案 0 :(得分:7)
因为您忘记了INSERT INTO
部分的陈述。等;
INSERT INTO tableName(musteriadi,musterisoyadi,gsm,email,sirketadi,Adres,Notlar)
但更重要的是,总是使用parameterized queries。这种字符串连接对SQL Injection攻击开放。
还可以使用using
statement来处理您的连接并自动命令 ,而不是手动调用Close
方法。
using(var baglanti = new SqlConnnection(yourConnectionString))
using(var cmd = baglanti.CreateCommand())
{
cmd.CommandText = @"INSERT INTO tableName(musteriadi,musterisoyadi,gsm,email,sirketadi,Adres,Notlar)
VALUES(@ad, @soyad, @gsm, @email, @sirket, @adres, @notlar)";
// Add your parameters values with Add method considering their types and size.
baglanti.Open();
cmd.ExecuteNonQuery();
}