我正在尝试使用C#将数据插入Microsoft SQL Server DB,并且insert命令运行良好,并且没有错误或异常。但是,当我在SQL Server中检查数据库时,对表没有影响,并且记录也没有插入表中。这是我尝试的代码:
try { SqlConnection con1 = new SqlConnection(); con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true"; con1.Open(); SqlCommand cm1 = new SqlCommand(); cm1.Connection = con1; cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','@" + update.Message.Chat.Username + "','" + req1.Status + "')"; con1.Close(); } catch(Exception e) { Console.WriteLine(e.Message); continue; }
同样,当我手动将数据插入数据库并运行如下所述的select命令时,我得到了正确的答案,但是对于insert命令却没有。
SqlConnection con2 = new SqlConnection(); con2.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true"; con2.Open(); SqlDataAdapter da1 = new SqlDataAdapter("select * from Users where ChatID='" + update.Message.Chat.Id.ToString() + "'", con2); DataSet ds1 = new DataSet(); da1.Fill(ds1); con1.Close();
请帮助我解决此问题。
顺便说一句,我知道这种插入是不安全的,我想告诉你,这只是一个演示,我将确保它可以防止 sql注入。
您不在任何地方执行命令。你需要:
cm1.ExecuteNonQuery();
在代码中,您正在创建一个SqlCommand对象,然后SqlConnection将其与之关联,但是在实际执行该命令的位置却没有。您的代码应如下所示:
SqlCommand
SqlConnection
SqlConnection con1 = new SqlConnection(); con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true"; con1.Open(); SqlCommand cm1 = new SqlCommand(); cm1.Connection = con1; cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','@" + update.Message.Chat.Username + "','" + req1.Status + "'"; cm1.ExecuteNonQuery(); con1.Close();
除了SQLInjection漏洞外,您还应考虑在语句中包含SqlCommand和SqlConnection对象using,以确保正确处置非托管资源。
using