简体   繁体   中英

How to insert dataGridView row text into database in c#

I am trying to transfer a full table text into my database and I figured I could use foreach loop. but I end up getting an error.

this is the code that I have so far:

        private void button1_Click(object sender, EventArgs e){

           foreach (DataGridViewRow dr in dataGridView1.Rows)
        {
            string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
            string Query = "Update TopShineDB.Table1 set Time = '" + dr.Cells[0].Value + "', CarColorNumber = '" + dr.Cells[1].Value + "', Interior = '" + dr.Cells[2].Value + "', Exterior = '" + dr.Cells[3].Value + "', CPlastic = '" + dr.Cells[4].Value + "', MPlastic = '" + dr.Cells[5].Value + "', SPlastic = '" + dr.Cells[6].Value + "', PlasticB = '" + dr.Cells[7].Value + "', WashExt = '" + dr.Cells[8].Value + "', WashEng = '" + dr.Cells[9].Value + "', WashTrunk = '" + dr.Cells[10].Value + "', WashSeats = '" + dr.Cells[11].Value + "', SeatsRmv = '" + dr.Cells[12].Value + "', SeatsFit = '" + dr.Cells[13].Value + "', Notes = '" + dr.Cells[14].Value + "', where Time = '" + dr.Cells[0].Value + "' ;";  
            MySqlConnection conn = new MySqlConnection(constring);
            MySqlCommand command = new MySqlCommand(Query, conn);
            MySqlDataReader myReader;

            try
            {
                conn.Open();
                myReader = command.ExecuteReader();
                MessageBox.Show("Worker Successfully Added");
                while (myReader.Read())
                {

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
}

and when I run the application I get this error in error box:

you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near '(Time, CarColorNumber, Interior, Exterior, CPlastic,...)

what am I doing wrong? thanks for the help.

As explained in my comment above you have a syntax error because there is a comma before the WHERE statement., but just removing that comma will not solve your problem because the word TIME is a reserved keyword and you shouldn't use it for your columns name. This problem could be fixed adding backticks ` before and after the keyword. (Or better changing the column name)

However, concatenating string to form your sql text creates other possible errors because if any of your input values contains a single quote then the whole string built by your code becomes again an invalid sql text.

Also the worst problem of the string concatenation approach is allowing malicious user to use a well known hacking tecnique called Sql Injection .

To solve once and for all your problems you should try to write a parameterized query like this one

private void button1_Click(object sender, EventArgs e)
{
    string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";

    // Prepare a string where you insert parameter's placeholders instead of
    // concatenating the grid values....
    string Query = @"Update TopShineDB.Table1 set CarColorNumber = @CarColorNumber, Interior = @Interior, 
                     Exterior = @Exterior , CPlastic = @CPlastic, MPlastic = @MPlastic, SPlastic = @SPlastic, 
                     PlasticB = @PlasticB, WashExt = @WashExt, WashEng = @WashEng, WashTrunk = @WashTrunk, 
                     WashSeats = @WashSeats, SeatsRmv = @SeatsRmv, SeatsFit = @SeatsFit, Notes = @Notes 
                     where `Time` = @Time";  

    // Using statement around connection and command to destroy
    // these objects at the end of the using block               
    using(MySqlConnection conn = new MySqlConnection(constring))
    using(MySqlCommand command = new MySqlCommand(Query, conn))
    {
        conn.Open();

        // Create the list of parameters required by the query
        // Notice that you should use the appropriate MySqlDbType
        // for the field receiving the value.
        command.Parameters.Add("@Time", MySqlDbType.VarChar); 
        command.Parameters.Add("@CarColorNumber", MySqlDbType.VarChar);

        ..... create all the other parameters leaving the value null

        try
        {

            foreach(DataGridViewRow dr in dataGridView1.Rows)
            {
                // Inside the loop update the parameters' values
                // with data extracted by the current row...
                command.Parameters["@Time"].Value = dr.Cells[0].Value; 
                command.Parameters["@CarColorNumber"].Value = dr.Cells[1].Value;

                 ..... set the value for all other parameters ....

                // ExecuteNonQuery for INSERT/UPDATE/DELETE, 
                // ExecuteReader works but it is specific for reading
                command.ExecuteNonQuery();      
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }   
 }

Another point to note is the update on the Time field. It is updated with the same value that you use in the where clause so there is no need to update it.

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