Ashwini Nemade
Ashwini Nemade

Reputation: 153

update query not working c# winform

My data is not being updated in database table. This is my code

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");

}

This is my table where I want to update data

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
);

Upvotes: 0

Views: 359

Answers (2)

Amrita Srivastava
Amrita Srivastava

Reputation: 384

you are using this query

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

here you are using '' in id also whereas usually id is of integer datatype. So id will not be there in the quotes. Also check your final query and run that final query in mssql. That will not bcause of this error.

Upvotes: 0

Richardissimo
Richardissimo

Reputation: 5775

Use parameters to avoid SQL injection attacks, either intentionally or unintentionally. It could be causing your error, depending on what the values are in the concatenated strings.

Unrelated tips: SqlConnection and SqlCommandand are IDisposable so should be in using blocks. The if test should be redundant, since Open will complain if it fails. All of the ToString methods being called on the Text properties are redundant as they are already strings. Consider adding a tag for to this question, to target the right expertise.

Upvotes: 3

Related Questions