简体   繁体   中英

MySql alter table in c# error

I am trying to perform

ALTER TABLE

command in my app, but when running, I am getting this error

 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 'VARCHAR(10) NOT NULL' at line 1

Here is my code:

for (int k = 0; k < dlzkaTab; k++)
{
 string query1 = "ALTER TABLE reflextime ADD " + atributes[k] + " VARCHAR(10) NOT NULL";
 MySqlCommand cmd = new MySqlCommand(query1, conect);
 cmd.ExecuteScalar();
 }

Can anyone please help me?

EDIT:

Here is full code. In the firs for loop I am reading first row from xls file and I am putting it into array atributes. As you can see, I was trying to print out every loaded cell. It worked well (It was printing correct values). However after this for loop the array is printing nothing (empty messagebox).

  for (int j = 2; j < colCount; j++)
  {
   string atr = xlRange.Cells[1, j].Text;
   atributes[j]=atr;
   MessageBox.Show(atributes[j]);
  }

 MessageBox.Show("Súbor načítaný");

 int dlzkaTab = atributes.Length;

 MessageBox.Show(atributes[1]);  //empty messagebox

 for (int k = 0; k < dlzkaTab; k++)
 {
 string query1 = "ALTER TABLE reflextime ADD COLUMN " + atributes[k] + " VARCHAR(10) NOT NULL";
 MySqlCommand cmd = new MySqlCommand(query1, conect);
 cmd.ExecuteScalar();

 } 

I think you are trying to add a column to the table.

You missed COLUMN keyword in the statement before column name that is being added.

"ALTER TABLE reflextime ADD COLUMN " + atributes[k] + " VARCHAR(10) NOT NULL"

You need to use ExecuteNonQuery instead of ExecuteScalar

And also check your each atributes[k] fro value exist or not

Try this

 for (int k = 0; k < dlzkaTab; k++)
 {
 string query1 = "ALTER TABLE reflextime ADD " + atributes[k] + " VARCHAR(10) NOT NULL";
 MySqlCommand cmd = new MySqlCommand(query1, conect);
 cmd.ExecuteNonQuery();
 }

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