How to Wrap dynamic string variables in double quoutes - json

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);

Related

c# How do I solve error mysql the used command is not allowed 1148?

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.

Insert from code or store procedure mysql

Well i have to do a series of updates and inserts.
I have this code on vb.net
Dim posicion_id As Integer = MysqlObj.ejecutarInsert("INSERT INTO posicion (dispositivoid, mensajeid, fechahora, longitud, latitud, altura, velocidad, direccion, resultadoid, descripcion, gpsweek, gpsseconds, notificacionenviada, positiontype) VALUES (" + msj.dispositivoid + "," + msj.mensajeid + ",'" + msj.fechahora + "','" + msj.longitud + "','" + msj.latitud + "'," + msj.altura + "," + msj.velocidad + "," + msj.direccion + "," + msj.resultadoid + ",'" + msj.descripcion + "'," + msj.gpsweek + "," + msj.gpsseconds + "," + msj.notificacionenviada + "," + msj.positiontype + "); SELECT LAST_INSERT_ID()").ToString()
If (Integer.Parse(msj.mensajeid) > 0) Then
MysqlObj.ejecutarInsert("INSERT INTO mensajedescripcion (mensajeid, fechahora, dispositivoid, secuencia) VALUES (" + msj.mensajeid + ",'" + msj.fechahora + "'," + msj.dispositivoid + ",0)")
End If
MysqlObj.ejecutarUpdate("UPDATE dispositivo SET ultimoMensaje = '" + msj.fechahora + "', fechanotificacion = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE dispositivoid = " + msj.dispositivoid)
If (MysqlObj.hasRows("SELECT * FROM posicion_current WHERE dispositivoid = " + msj.dispositivoid)) Then
MysqlObj.ejecutarUpdate("UPDATE posicion_current SET posicionid = " + posicion_id.ToString() + ", mensajeid = " + msj.mensajeid + ", fechahora = '" + msj.fechahora + "', longitud = '" +
msj.longitud + "', latitud = '" + msj.latitud + "', altura = " + msj.altura + ", velocidad = " + msj.velocidad + ", direccion = " + msj.direccion + ", resultadoid = " + msj.resultadoid + ", descripcion = '" + msj.descripcion +
"', gpsweek = " + msj.gpsweek + ", gpsseconds = " + msj.gpsseconds + ", notificacionenviada = " + msj.notificacionenviada + " WHERE dispositivoid = " + msj.dispositivoid)
Else
MysqlObj.ejecutarInsert("INSERT INTO posicion_current (posicionid, mensajeid, fechahora, longitud, latitud, altura, velocidad, direccion, resultadoid, descripcion, gpsweek, gpsseconds, notificacionenviada) VALUES (" + posicion_id + "," + msj.mensajeid + ",'" + msj.fechahora + "','" + msj.longitud + "','" + msj.latitud +
"'," + msj.altura + "," + msj.velocidad + "," + msj.direccion + "," + msj.resultadoid + ",'" + msj.descripcion + "'," + msj.gpsweek + "," + msj.gpsseconds + "," + msj.notificacionenviada + ")")
Is it better for performance to do it like that or a single stored procedure that receives all data and does each insert update
DECLARE existss INT DEFAULT 0;
INSERT INTO posicion (dispositivoid, mensajeid, fechahora, longitud, latitud, altura, velocidad, direccion, resultadoid, descripcion, gpsweek, gpsseconds, notificacionenviada, positiontype)
VALUES (_dipositivoid, _mensajeid, _fechahora, _longitud, _latitud, _altura, _velocidad, _direccion, 0, _descripcion, 0, 0, 1, 4219724);
SELECT COUNT(*) INTO #existss FROM posicion_current WHERE dispositivoid = _dispositivoid
IF (#existss > 0) THEN
UPDATE posicion_current SET posicionid = LAST_INSERT_ID(), mensajeid = _mensajeid, fechahora = _fechahora, longitud = _longitud, latitud = _latitud,
altura = _altura, velocidad = _velocidad, direccion = _direccion, resultadoid = 0, descripcion = _descripcion, gpsweek = 0, gpsseconds = 0, notificacionenviada = 1
WHERE dispositivoid = _dispositivoid;
ELSE
INSERT INTO posicion_current (dispositivoid, mensajeid, fechahora, longitud, latitud, altura, velocidad, direccion, resultadoid, descripcion, gpsweek, gpsseconds, notificacionenviada)
VALUES (_dipositivoid, _mensajeid, _fechahora, _longitud, _latitud, _altura, _velocidad, _direccion, 0, _descripcion, 0, 0, 1);
END IF;
UPDATE dispositivo SET ultimoMensaje = _fechahora, fechanotificacion = NOW() WHERE dispositivoid = _dispositivoid;
INSERT INTO mensajedescripcion (mensajeid, fechahora, dispositivoid, secuencia) VALUES (_mensajeid, _fechahora, _dispositivoid, 0);
Change the COUNT(*)...IF...UPDATE...ELSE...INSERT into
INSERT ... ON DUPLICATE KEY UPDATE ...
That will be faster and simpler.

Mirth: cannot execute database query

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

DataAdapter.Update() doesn't work to update

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.

Insert into MySql failed

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.