1

I'm trying to load data to a mysql table, when I run the code in the MySql Workbench, it works fine, but when I try to run it in my c# application, I get this error:

Fatal error encountered during command execution.

Here's my code:

mConn.Open(); //Opens the connection
string query = "delete from time; alter table time auto_increment=1; LOAD DATA INFILE 'C://time_u.txt' INTO TABLE `time` CHARACTER SET 'utf8' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES (@col2, @col3) set date = @col2, hour = @col3;";
WriteDataToDataBase(query); //This guy just executes the command.ExecuteNonQuery();
mConn.Close();

Ps: I have 3 columns, the first one is a primary key (id) which I can't import, it needs to go up by one automatically, the second is the date (varchar) and third is the hours (varchar as well).

UPDATE
I tried to change the LOAD DATA code and I found out that the part that gives the error is this part: (@col2, @col3) set date = @col2, hour = @col3;. When I remove this, the code works (it doesn't work in my case because without this it tries to put data in the Primary key) but it doesn't show that first error.

Thanks...

6
  • Side note: delete from time; alter table time auto_increment=1; can be better replaced with truncate table time Commented May 22, 2018 at 13:19
  • @RaymondNijland thanks for your reply, I'll try to use another method to execute. I'll keep you updated if it works. Commented May 22, 2018 at 13:20
  • i don't believe ExecuteNonQuery() running MySQL client supports multiple statements separated with semicons (;) Commented May 22, 2018 at 13:21
  • @RaymondNijland I tried to execute only the LOAD DATA code but it gave me the same error Commented May 22, 2018 at 13:28
  • Have you tried to execute your commands step by step? Delete, then alter, then load data ... Next test could be combine delete and alter statements. Still get an error? What Exception is thrown? Stacktrace? Commented May 22, 2018 at 13:48

1 Answer 1

1

MySql.Data is treating @col2, @col3 as (undefined) query parameters, which is causing this error. One workaround would be to add AllowUserVariables=true to your connection string.

The other workaround would be to avoid the variables and just load directly into the columns you want:

LOAD DATA INFILE 'C://time_u.txt'
INTO TABLE time
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(date, hour);
Sign up to request clarification or add additional context in comments.

1 Comment

Finally got it working using your second workaround. Thank you very much!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.