简体   繁体   中英

Column count doesn't match value count at row 1 c#

I am trying to load data from xls to mysql database, but, I am getting this error:

Column count doesn't match value count at row 1

In this cycle, I am trying to select iteratively all values from 2-nd column of my excel and insert it into db (excluding first row, because first row in xls is the name of my column). rowcount is 487.

   for (int x = 2; x < rowCount; x++)
        {

            string str = xlRange.Cells[x, 2].Text;

            string query = "INSERT INTO feture (F1) VALUES (" + str + ")";
            MessageBox.Show(x.ToString());
            MySqlCommand cmd = new MySqlCommand(query, conect);
            cmd.ExecuteScalar();

        }

So where do I have problem? Thx

String values have to be surrounded by single quotes ' .

Change :

string query = "INSERT INTO feture (F1) VALUES (" + str + ")";

To :

string query = "INSERT INTO feture (F1) VALUES ( '" + str + "' )";

You need to use single quotes with your value but more importantly, you should use parameterized queries instaed of string concatenation:

string query = "INSERT INTO feture (F1) VALUES (@value)";
MySqlCommand cmd = new MySqlCommand(query, conect);
cmd.Parameters.AddWithValue("@value", str);
cmd.ExecuteScalar();

If you are wondering why do some research about SQL Injection .

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