更新查询无法正常工作c#winform

问题描述 投票:0回答:2

我的数据未在数据库表中更新。这是我的代码

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
);
c# sql sql-server winforms
2个回答
3
投票

使用参数可以有意或无意地避免SQL注入攻击。它可能会导致您的错误,具体取决于连接字符串中的值。

不相关的提示:SqlConnectionSqlCommandand是IDisposable所以应该在using块。 if测试应该是多余的,因为如果失败,Open会抱怨。在Text属性上调用的所有ToString方法都是多余的,因为它们已经是字符串。考虑为此问题添加标签,以确定正确的专业知识。


0
投票

您正在使用此查询

    "UPDATE marks SET subjects='" + subjects + "',smarks='" + marks + "',percentage='" + percentage + "',total='" + total + "' WHERE idno='" + id + "'";

这里你在id中使用'',而通常id是整数数据类型。所以id不会出现在引号中。还要检查最终查询并在mssql中运行最终查询。这不会是因为这个错误。

© www.soinside.com 2019 - 2024. All rights reserved.