When trying to create a string to hold the following query for importing a CSV file into MySql the query itself brakes the string i am trying to create.
string Query = "load data local infile" + " " + "'" + Filename + "'" + " " + "into table" + " " + Table + "'FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES";
Is there anything i do about the ENCLOSED BY '"' part?
Thanks
You need to escape the double quote char using \ : "\""
string Query = "load data local infile" + " " + "'" + Filename + "'" + " " + "into table" + " " + Table + "' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES";
This is the full method.
public static void MySqlCSVImport(string Filename, string Table, string Server, string Database, string User, string Password)
{
try
{
//enclosed by '"'
string connectionString = "server=" + Server + ";database=" + Database + ";User Id=" + User + ";password=" + Password + "";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
mySqlConnection.Open();
string Query = "load data local infile" + " " + "'" + Filename + "'" + " " + "into table" + " " + Table + "' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES";
MySqlCommand cmd = new MySqlCommand(Query, mySqlConnection);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Fixed the issue by the following method if it helps anyone.
public static void MySqlCSVImport(string Filename, string Table, string Server, string Database, string User, string Password, string Port)
{
try
{
//enclosed by '"'
string FixFilePath = Filename.Replace(#":\", ":\\");
string c = "'" + "\\n" + "'";
string d = ";";
string connectionString = "server=" + Server + ";database=" + Database + ";User Id=" + User + ";password=" + Password + "";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
mySqlConnection.Open();
string Query = "load data local infile" + " " + "'" + FixFilePath + "'" + " " + "into table" + " " + Table + " FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY" + " " + c + d;
MySqlCommand cmd = new MySqlCommand(Query, mySqlConnection);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Related
I am executing a SQL query from C# but get the error:
MySql.Data.MySqlClient.MySqlException: 'The used command is not allowed with this MariaDB version'
Any help / pointers would be appreciated.
Here is my code:
private bool SaveCsvLines(string strFileName)
{
bool bResult = false;
if (ConnectToDatabase())
{
// Here we load the string variable with the SQL we want to run
string strLineInsert = "LOAD DATA LOCAL INFILE " +
"'" + strFileName + "' " +
"INTO TABLE pfetest1.maerskInvoiceLine " +
"FIELDS TERMINATED BY ',' " +
"LINES TERMINATED BY '\r\n' " +
"IGNORE 1 LINES " +
"(container, " +
"size, " +
"vessel, " +
"portOfLoad, " +
"porCityCode, " +
"portOfDischarge, " +
"podCityCode, " +
"postCode, " +
"invoiceNo, " +
"SET createdTimestamp = NOW(), " +
"createdUserId = 1, " +
"updatedTimestamp = NOW(), " +
"updatedUserId = 1, " +
"headerId = " + m_iFileId + ", " +
"eta = STR_TO_DATE(#eta, '%d/%m/%Y')";
//Now we execute that statement
MySqlCommand command = new MySqlCommand(strLineInsert, con);
bResult = (command.ExecuteNonQuery() == 1);
}
return bResult;
}
Switched to using MySQLBulkloader. That way I can define the columns etc. first then pump the data in.
My problem is: if I change the query string below to select * from table;, it works fine. but if I execute the query string below, it throws an error:
SQL error: Invalid column number. Cannot less than or equal zero.
This is the code:
columnHeader = " 'id', 'pat_name', 'pat_age' ";
var filename = $('serType') + $('serId') + ".csv";
var reporting_exportQuery = "select " + columnHeader +
" union all " +
"select * " +
"from " + $('serType') +
" into outfile 'C://mytest/reports/service reports/"+$('serType') + "/" + "" + filename + "' " +
"fields terminated by ',' " +
"lines terminated by '\\n';";
var test = "select * from Age;";
reporting_DBConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.jdbc.Driver',:D);
logger.info(reporting_exportQuery);
var result = reporting_DBConn.executeCachedQuery(reporting_exportQuery);
You are adding(union) one column columnHeader with all columns (*) from table. You can do like this
SELECT 'columnHeader',table_alias.* FROM TABLE table_alias...
var filename = $('serType') + $('serId') + ".csv";
var reporting_exportQuery =
"select 'columnHeader',table_alias.* " +
"from " + $('serType') table_alias+
" into outfile 'C://mytest/reports/service reports/"+$('serType') + "/" + "" + filename + "' " +
"fields terminated by ',' " +
"lines terminated by '\\n';";
var test = "select * from Age;";
reporting_DBConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.jdbc.Driver','jdbc:mysql://localhost:3310/cnwlreports', :D);
logger.info(reporting_exportQuery);
var result = reporting_DBConn.executeCachedQuery(reporting_exportQuery);
My guess is columnHeader have a diferent number of columns than select * in the union part.
Step to debug.
print the result string reporting_exportQuery
try running that string on the MySql.
Added:
First Select doesn't have FROM part
.
var reporting_exportQuery =
"select " + columnHeader +
"FROM SomeTable" <--- need FROM
" union all " +
"select " + columnHeader + <--- need same columns
Can someone help me with the problem that I'm having now?
I have a set of question(survey). When the user done the survey, it will insert to my database.
However, right now, when I submit the survey, it doesn't insert the result into my database.
here is my code:
try {
//Process - Query from SQL
String strSqlnsert = "INSERT INTO Customers (MembershipID, Contact, Email, Address, SurveyStatus, Subscription) VALUES"
+ " ('"+ member_ID + "', " + contact_num + ", '" + email_add + "', '" + mail_add + "' , " + radio_group + "," + receive_info + ")";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/customers", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strSqlnsert);
I've also add in the library for the JDBC in the library folder.
It seems the non numeric values aren't quoted
Instead of
" + email_add + ",
try
'" + email_add + "',
In the below insert statement
INSERT INTO table (field1, field2) VALUES ( 5, 'this is a string');
the 'this is a string' is wrapped in quotes, because field2 is of type VARCHAR. field1 is INT so the value assigned to it (5) doesn't need quoting.
The VALUES list must be in braces too and again, non numeric values must be quoted:
String strSqlnsert = "INSERT INTO Customers (MembershipID, Contact, Email, Address, SurveyStatus, Subscription) VALUES (" + member_ID + ", " + contact_num + ", '" + email_add + "', '" + mail_add + "', '" + radio_group + "', '" + receive_info + "')";
Try to make a prepared statement where you can call setInt or setString method of preparedStatement class . so it will automatically remove string or numeric confusion at all.
BTW preparedStatement is the best way to pass parameter in sql query.don't use Statement class for parameter sql query.
my sql statments are as follows
the insert statement only works
update and delete statements don't work
Purchase_InvoiceNo is a primary key column of Purchase table
i get this value like this and insert its value to PurchaseProduct table
"SELECT IDENT_CURRENT ('Purchase') AS [Purchase_InvoiceNo]"
string deletecmd_PurchaseProduct =
#"DELETE FROM PurchaseProduct " +
"PurchaseProduct_No=#PurchaseProduct_No and "+
"Purchase_InvoiceNo=#Purchase_InvoiceNo ";
string updatcmd_PurchaseProduct =
"UPDATE PurchaseProduct "
+ " SET "
+ " PurchaseProduct_SerialNo =#PurchaseProduct_SerialNo"
+ ", Purchase_InvoiceNo =#Purchase_InvoiceNo"
+ ", ProductNo =#ProductNo"
+ " PurchaseProduct_Quantity =#PurchaseProduct_Quantity "
+ ", PurchaseProduct_Unit =#PurchaseProduct_Unit"
+ ", PurchaseProduct_Price =#PurchaseProduct_Price"
+ " Where "
+ " PurchaseProduct_No=#PurchaseProduct_No";
string insertcmd_PurchaseProduct = "INSERT INTO PurchaseProduct" +
"(" +
" PurchaseProduct_SerialNo"+
",Purchase_InvoiceNo" +
",ProductNo" +
",PurchaseProduct_Quantity " +
",PurchaseProduct_Price" +
",PurchaseProduct_Unit" + //6
")" +
"Values" +
"(" +
" #PurchaseProduct_SerialNo"+
",#Purchase_InvoiceNo" +
",#ProductNo " +
",#PurchaseProduct_Quantity " +
",#PurchaseProduct_Price" +
",#PurchaseProduct_Unit" + //6
");";
Your Delete command appears to be incomplete:
string deletecmd_PurchaseProduct =
#"DELETE FROM PurchaseProduct " +
"PurchaseProduct_No=#PurchaseProduct_No and "+
"Purchase_InvoiceNo=#Purchase_InvoiceNo ";
should be:
string deletecmd_PurchaseProduct =
#"DELETE FROM PurchaseProduct WHERE" +
"PurchaseProduct_No=#PurchaseProduct_No and "+
"Purchase_InvoiceNo=#Purchase_InvoiceNo ";
I can't see why the INSERT should fail unless you're inserting a duplicate primary key value or you're not inserting data into a non-nullable field which does not have a default.
string updatcmd_PurchaseProduct =
"UPDATE PurchaseProduct "
+ "SET PurchaseProduct_SerialNo = #PurchaseProduct_SerialNo, "
+ "Purchase_InvoiceNo = #Purchase_InvoiceNo, "
+ "ProductNo = #ProductNo, "
+ "PurchaseProduct_Quantity = #PurchaseProduct_Quantity, "
+ "PurchaseProduct_Unit = #PurchaseProduct_Unit, "
+ "PurchaseProduct_Price = #PurchaseProduct_Price "
+ "Where PurchaseProduct_No = #PurchaseProduct_No";
There was a missing comma above.
Hy everyone i have a problem when i try to insert something in database. The DB method is:
public static void insertInEntries(String NrDeOrdine, String NrDocument,String Data, String Emitent, String Continut, String Observatii)
throws SQLException {
Statement statement = (Statement) conn.createStatement();
try {
statement.executeUpdate("INSERT INTO Intrari " + "VALUES("
+ NrDeOrdine + "," + NrDocument + "," + Data + ","
+ Emitent + "," + Continut + "," + Observatii + ");");
System.out.println("Done");
} catch (SQLException e) {
System.err.println("Eroare:" + e);
}
}
In fxml i have a button, which action this methon on click!
#FXML protected void eadaugareIn(ActionEvent event) throws SQLException {
DBConnection.connect();
DBConnection.getConnection();
try
{
DBConnection.insertInEntries(enrOrdInput.getText().toString(), enrDocInput.getText().toString(), edataInput.getText().toString(), eemitentInput.getText().toString(), econtinutTextArea.getText().toString(), eobsTextArea.getText().toString());
}
catch(SQLException e){
System.err.println("Eroare:" + e);
}
}
So everything i am putting in this field seems to get me the error if in the first textfield the text is " sa " i put into the textfields:
Eroare:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'sa' in 'field list'
How i could solve this? Thank you very much!
EDIT: I found the answer a few hours ago:
statement.executeUpdate("INSERT INTO `intrari`(`NrDeOrdine`, `NrDocument`, `Data`, `Emitent`, `Continut`, `Observatii`)
VALUES("+ '"' + NrDeOrdine + '"' + "," + '"' + NrDocument + '"' + "," + '"'
+ Data + '"' + "," + '"' + Emitent + '"' + "," + '"' + Continut + '"' + ","
+ '"' + Observatii + '"' + ");");
Add logging to your insertInEntries method:
System.out.println("INSERT INTO Intrari " + "VALUES("
+ NrDeOrdine + "," + NrDocument + "," + Data + ","
+ Emitent + "," + Continut + "," + Observatii + ");");
Most probably looking at the output will give you solution.