简体   繁体   中英

How can i update data in c#

  1. I'm working in Visual Studio 2019 In c
  2. I have problem with updating data to database
  3. I use local Visual Studio SQL database

private void button1_Click(object sender, EventArgs e) { String source = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30"; SqlConnection con = new SqlConnection(source); con.Open();

        String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = "+ int.Parse(textBox1.Text);
        SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())
        {
            textBox2.Text = (dr["Name"].ToString());
            textBox3.Text = (dr["Kor"].ToString());
            label4.Text = (dr["Kor"].ToString());
            label5.Text = (dr["Kor"].ToString());

            int s = 11;
            string y = (dr["Kor"].ToString());

            label4.Text = (dr["Kor"].ToString());
            x = Int32.Parse(label4.Text);
            x = x + 0;

            label6.Text = (x.ToString());
            
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        String source = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
        SqlConnection con = new SqlConnection(source);
        con.Open();
        x = x + 1;
        label6.Text = (x.ToString());
        String st = "UPDATE supplier SET Kor = " + label6.Text + " WHERE Id = " + textBox1.Text;
    }    
  

Add these lines

SqlCommand cmd = new SqlCommand(st, con);
int result = cmd.ExecuteNonQuery();

Please put a breakpoint and check the value of st , is it generating the valid query.

I would suggest to use stored procedure and pass the parameters from code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM