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.
Related
I have static body which works great. But how I can wrap the same dynamic strings with double quotes - >""
Static Body
var body = #"{" + "\n" +
#" ""profile"": {" + "\n" +
#" ""firstName"": ""Isaac1""," + "\n" +
#" ""lastName"": ""Brock1""," + "\n" +
#" ""email"": ""isaac1.brock#example.com""," + "\n" +
#" ""login"": ""isaac1.brock#example.com""," + "\n" +
#" ""mobilePhone"": ""555-415-1337""" + "\n" +
#" }" + "\n" +
#"}";
Dyanmic Content (FirstName, LastName, Email, MobilePhone should all be wrapped with "")
var body1 = #"{" + "\n" +
#" ""profile"": {" + "\n" +
#" ""firstName"": "+ firstName + "," + "\n" +
#" ""lastName"": "+lastName+"," + "\n" +
#" ""email"": "+email+"," + "\n" +
#" ""login"": "+email+"," + "\n" +
#" ""mobilePhone"": "+mobilePhone+"" + "\n" +
#" }" + "\n" +
#"}";
you can wrap a variable using string escape syntax " \ ""
var body1 = #"{" + "\n" +
#" ""profile"": {" + "\n" +
#" ""firstName"": " + "\"" + firstName + "\"" + "," + "\n" +
#" ""lastName"": " + "\"" + lastName + "\"" + "," + "\n" +
//.....
#" }" + "\n" +
#"}";
but IMHO it is more safe to create a json object and after this to serialize it to a json string , using Newtonsoft.Json for example
var body = new JObject {
["profile"]=new JObject {
["firstName"] = firstName,
["lastName"] = lastName
//...
}
}.ToString();
or you can replace JObject with an anonymos class and serialize after creaing.
var body = JsonConvert.SerializeObject(new
{
profile = new
{
firstName = firstName,
lastName = lastName
//...
}
}, Newtonsoft.Json.Formatting.Indented);
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
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.
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);
}
}