繁体   English   中英

如何在C#中将dataGridView行文本插入数据库

[英]How to insert dataGridView row text into database in c#

我试图将一个完整的表文本传输到我的数据库中,我认为我可以使用foreach循环。 但我最终得到一个错误。

这是我到目前为止的代码:

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

当我运行该应用程序时,在错误框中显示此错误:

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,...)

我究竟做错了什么? 谢谢您的帮助。

正如我上面的评论中所解释的那样,您有一个语法错误,因为WHERE语句之前有一个逗号。但是仅删除该逗号并不能解决您的问题,因为单词TIME是保留关键字,您不应在列中使用它名称。 可以在关键字之前和之后添加反引号`来解决此问题。 (或者更好地更改列名)

但是,将字符串连接起来以形成sql文本会产生其他可能的错误,因为如果任何输入值包含单引号,那么由代码构建的整个字符串将再次变为无效的sql文本。

字符串连接方法最严重的问题是允许恶意用户使用一种称为Sql Injection的众所周知的黑客技术。

为了一劳永逸地解决您的问题,您应该尝试编写一个像这样的参数化查询

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

要注意的另一点是“时间”字段上的更新。 它使用与where子句中使用的值相同的值进行更新,因此无需对其进行更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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