I am using JSON format to save data in my c++ program , i want to send it to MySql database (the table tab has one column with type : TEXT) but the query failed (tested also VARCHAR and CHAR )
this is a part of the code since we are not interrested in the rest
string json_example = "{\"array\":[\"item1\",\"item2\"], \"not an array\": \"asdf\"}";
mysql_init(&mysql); //initialize database connection
string player="INSERT INTO tab values (\"";
player+= json_example;
player += "\")";
connection = mysql_real_connect(&mysql,HOST,USER,PASSWD,DB,0,NULL,0);
// save data to database
query_state=mysql_query(connection, player.c_str()); // use player.c_str()
to show the final query that will be used : cout << player gives :
INSERT INTO tab values ("{"array":["item1","item2"], "not an
array": "asdf"}")
using for example string json_example = "some text"; is working
but with the json format it is not working , maybe the problem came from the use of curly bracket {} or double quotes "" but i haven't find a way to solve it .
i'm using :
mysql Ver 14.14 Distrib 5.5.44, for debian-linux-gnu (armv7l) under raspberry pi 2
Any help will be appreciated , thanks .
Use a prepared statement. See prepared statements documentation in the MySQL reference manual.
Prepared statements are more correct, safer, possibly faster, and keep your code cleaner. You get all those benefits and don't need to escape anything. There is hardly a reason not to use them.
Something like this might work. But take it with a grain of salt, because I have not tested or compiled it. It should just give you the general idea:
MYSQL_STMT* const statement = mysql_stmt_init(&mysql);
std::string const query = "INSERT INTO tab values(?)";
mysql_stmt_prepare(statement, query, query.size());
MYSQL_BIND bind[1] = {};
bind[0].buffer_type = MYSQL_TYPE_STRING;
bind[0].buffer = json_example.c_str();
bind[0].buffer_length = json_example.size();
mysql_stmt_bind_param(statement, bind);
mysql_stmt_execute(statement);
Related
I get a std::vector< std::vectorstd::string > and want to stream this to the database using pqxx::stream_to (pretty huge amount of data) e.g:
pqxx::work insert_tx(C);
pqxx::stream_to stream{
insert_tx,"CompTable",std::vector<std::string>{"TKey", "AKey"}};
for (auto&& row : vector_of_vectors)
{
auto val = std::make_tuple(row.at(3),row.at(2));
stream<<val;
}
stream.complete();
insert_tx.commit();
This works fine as long there is no "DATE" format needed.
I know i can do it with SQL statements e.g (".... VALUES ($1::date)",std::string) but this doesn't work with pqxx::stream_to
So does anyone know which c++ datatype or struct or whatever is compatible with the SQL data format?
Thank you for your time and ideas :)
It just works using the string format "yyyy/MM/dd" or "yyyy-MM-dd" or some other format, maybe the count of second (you can see it in java.sql.date).
I need help to normalize the field "DSC_HASH" inside a single column delimeted by colon.
Input:
Outuput:
I achieved what I needed with java transformation:
1) In java transformation I created 4 output columns: COD1_out, COD2_out, COD3_out and DSC_HASH_out
2) Then I put the following code:
String [] column_split;
String column_delimiter = ";";
String [] column_data;
String data_delimiter = ":" ;
Column_split = DSC_HASH.split(column_delimiter);
COD1_out = COD1;
COD2_out = COD2;
COD3_out = COD3;
for (int I =0; i < column_split.length; i++){
column_data = column_split[i].split(data_delimiter);
DSC_HASH_out = column_data[0];
generateRow();
}
There are no generic parsers or loop construct in Informatica that can take one record and output an arbitrary number of records.
There are some ways you can bypass this limitation:
Using the Java Transformation, as you did, which is probably the easiest... if you know Java :) There may be limitations to performance or multi-threading.
Using a Router or a Normalizer with a fixed number of output records, high enough to cover all your cases, then filter out empty records. The expressions to extract fields are a bit complex to write (an maintain).
Using the XML Parser, but you have to convert your data to XML before, and design an XML schema. For example your first line would be changed in (on multiple lines for readability):
<e><n>2320</n><h>-1950312402</h></e>
<e><n>410</n><h>103682488</h></e>
<e><n>4301</n><h>933882987</h></e>
<e><n>110</n><h>-2069728628</h></e>
Using SQL Transformation or Stored Procedure Transformation to use database standard or custom functions, but that would result in an SQL query for each input row, which is bad performance-wise
Using a Custom Transformation. Does anyone want to write C++ for that ?
The Java Transformation is clearly a good solution for this situation.
I have a snippet of code from my python 2.7 program:
cur.execute("UPDATE echo SET ? = ? WHERE ID = ?", (cur_class, fdate, ID,))
that when run, keeps throwing the following error:
sqlite3.OperationalError: near "?": syntax error
The program is supposed to insert today's date, into the class column that matches the student ID supplied. If I remove the first "?" like so and hard code the parameter:
cur.execute("UPDATE echo SET math = ? WHERE ID = ?", (fdate, ID,))
everything works just fine. I've googled all over the place and haven't found anything that works yet so I'm throwing out a lifeline.
I've tried single quotes, double quotes, with and without parenthesis and a few other things I can't remember now. So far nothing works other than hard coding that first parameter which is really inconvenient.
As a troubleshooting step I had my program print the type() of each of the variables and they're all strings. The data type of the the cur_class field is VARCHAR, fdate is DATE, and ID is VARCHAR.
Thanks to the tip from #Shawn earlier I solved the issue with the following code and it works great:
sqlcommand = "UPDATE echo SET " + cur_class + " = " + fdate + " WHERE ID = " + ID
cur.execute(sqlcommand)
This way python does the heavy lifting and constructs my string with all the variables expanded, then has the db execute the properly formatted SQL command.
I'm using RegEx in a MySQLi prepared statement to find any rows that contain only an integer in a particular field. I want to replace those integers with an empty string. I also want to ignore any rows that contain alphabetic characters in that field. However, my syntax seems to be wrong. Here is my PHP code:
$Empty = "";
$IntegersOnly = "[0-9]+";
$stmt = mysqli_prepare($db, "UPDATE MyTable set MyField = ? where REGEXP ?");
$bind = mysqli_stmt_bind_param($stmt, "ss", $Empty, $IntegersOnly);
$exec = mysqli_stmt_execute($stmt);
I'm getting the following error at the bind line: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given
So I believe my $stmt or $bind syntax is wrong.
Please consider that my programming experience is limited. I am hoping to use MySQLi (not PDO) and procedural programming (not OOP).
I'm using PHP 7 with a recent version of MariaDB, which is equivalent to MySQL
My apologies. I found the mistake. I should have used this:
$stmt = mysqli_prepare($db, "UPDATE MyTable set MyField = ? where MyField REGEXP ?");
In other words, I accidentally omitted MyField before REGEXP.
I want to select all the binary data from a column of a SQL database (SQL Server Enterprise) using C++ query. I'm not sure what is in the binary data, and all it says is .
I tried this (it's been passed onto me to study off from) and I honestly don't 100% understand the code at some parts, as I commented):
SqlConnection^ cn = gcnew SqlConnection();
SqlCommand^ cmd;
SqlDataAdapter^ da;
DataTable^ dt;
cn->ConnectionString = "Server = localhost; Database=portable; User ID = glitch; Pwd = 1234";
cn->Open();
cmd=gcnew SqlCommand("SELECT BinaryColumn FROM RawData", cn);
da = gcnew SqlDataAdapter(cmd);
dt = gcnew DataTable("BinaryTemp"); //I'm confused about this piece of code, is it supposed to create a new table in the database or a temp one in the code?
da->Fill(dt);
for(int i = 0; i < dt->Rows->Count-1; i++)
{
String^ value_string;
value_string=dt->Rows[i]->ToString();
Console::WriteLine(value_string);
}
cn->Close();
Console::ReadLine();
but it only returns a lot of "System.Data.DataRow".
Can someone help me?
(I need to put it into a matrix form after I extract the binary data, so if anyone could provide help for that part as well, it'd be highly appreciated!)
dt->Rows[i] is indeed a DataRow ^. To extract a specific field from it, use its indexer:
array<char> ^blob=dt->Rows[i][0];
This extracts the first column (since you have only one) and returns an array representation of it.
To answer the question in your code, the way SqlDataAdapter works is like this:
you build a DataTable to hold the data to retrieve. You can fill in its columns, but you're not required to. Neither are you required to give it a name.
you build the adapter object, giving it a query and a connection object
you call the Fill method on the adapter, giving it the previously created DataTable to fill with whatever your query returns.
and you're done with the adapter. At this point you can dispose of it (for example inside a using statement if you're using C#).