我的数据未在数据库表中更新。这是我的代码
string marks = textBox1.Text.ToString() + "," + textBox2.Text.ToString() + "," + textBox3.Text.ToString() + "," + textBox4.Text.ToString() + "," + textBox5.Text.ToString();
string subjects = label5.Text.ToString() + "," + label6.Text.ToString() + "," + label7.Text.ToString() + "," + label8.Text.ToString() + "," + label9.Text.ToString();
string total = label11.Text.ToString();
string percentage = label13.Text.ToString();
string id = textBox1.Text.ToString();
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\TECHNOGEEKZ\Desktop\USSv0.1\USSv0.1\USSv0.1\db\Database.mdf;Integrated Security=True");
con.Open();
if (con.State == ConnectionState.Open)
{
string q = "UPDATE marks SET subjects='" + subjects + "',smarks='" + marks + "',percentage='" + percentage + "',total='" + total + "' WHERE idno='" + id + "'";
SqlCommand com = new SqlCommand(q, con);
com.ExecuteNonQuery();
MessageBox.Show("Marks have been updated");
}
这是我要更新数据的表
CREATE TABLE [dbo].[marks]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[idno] INT NULL,
[subjects] VARCHAR (MAX) NULL,
[smarks] VARCHAR (MAX) NULL,
[percentage] VARCHAR (50) NULL,
[total] VARCHAR (50) NULL
);
答案 0 :(得分:3)
使用参数避免有意或无意的SQL注入攻击。可能会导致错误,具体取决于串联字符串中的值。
不相关的提示:SqlConnection
和SqlCommand
分别为IDisposable
,因此应放在using
块中。 if
测试应该是多余的,因为Open会在失败时进行投诉。在Text属性上调用的所有ToString方法都是多余的,因为它们已经是字符串了。考虑为此问题添加sql-server的标签,以定位正确的专业知识。
答案 1 :(得分:0)
您正在使用此查询
"UPDATE marks SET subjects='" + subjects + "',smarks='" + marks + "',percentage='" + percentage + "',total='" + total + "' WHERE idno='" + id + "'";
在这里,您还在id中使用'',而通常id是整数数据类型。所以id不会出现在引号中。还要检查最终查询,然后在mssql中运行该最终查询。那不会因为这个错误。