Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LOAD DATA INFILE with variables

I was tring to use the LOAD DATA INFILE as a sotred procedure but it seems it cannot be done. Then i tried the usual way of embedding the code to the application itself like so,

conn = new MySqlConnection(connStr);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd = conn.CreateCommand();
string tableName = getTableName(serverName);
string query = "LOAD DATA INFILE '" + fileName + "'INTO TABLE "+ tableName +" FIELDS TERMINATED BY '"+colSep+"' ENCLOSED BY '"+colEncap+"' ESCAPED BY '"+colEncap+"'LINES TERMINATED BY '"+colNewLine+"' ("+colUpFormat+");";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();

The generated query that gets saved in the string variable query is,

        LOAD DATA INFILE 'data_file.csv'INTO TABLE tbl_shadowserver_bot_geo FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'LINES TERMINATED BY '\n' (timestamp,ip,port,asn,@dummy,@dummy,@dummy,@dummy,@dummy,@dummy,url,agent,@dummy,@dummy,@dummy,@dummy,@dummy,@dummy,@dummy,@dummy,@dummy,@dummy,@dummy);

But now when i run the program it gives an error saying,

        MySQLException(0x80004005) Parameter @dummy must be defined first.

I dont know how to get around this, but when i use the same query on mysql itself directly it works fine. PLEASE help me..thank you very much :)

like image 637
Hasitha Shan Avatar asked Oct 11 '12 07:10

Hasitha Shan


People also ask

Which is more efficient load data insert?

LOAD DATA (all forms) is more efficient than INSERT because it loads rows in bulk.

What is load data infile?

The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed. If the LOCAL keyword is specified, the file is read from the client host. If LOCAL is not specified, the file must be located on the server.

How do you load data into a MySQL table?

mysql> LOAD DATA LOCAL INFILE '/path/pet. txt' INTO TABLE pet; If you created the file on Windows with an editor that uses \r\n as a line terminator, you should use this statement instead: mysql> LOAD DATA LOCAL INFILE '/path/pet.

How do I import a csv file into MySQL?

In the Format list, select CSV. Changing format-specific options. If the csv file is delimited by a character other than a comma or if there are other specifications to the csv files, we can change it in this portion. Click Go to start importing the csv file and the data will be successfully imported into MySQL.


1 Answers

I found the solution myself, it is to set this condition,

      Allow User Variables=true;

in the connection string that will allow to use @parameter values in a query :)

Thank you for the responses :)

like image 70
Hasitha Shan Avatar answered Sep 19 '22 14:09

Hasitha Shan