In MySQL there is the mysql_real_escape_string function.
Is there an such for MS SQL to correctly handle strings like this one?
SELECT * FROM MyTable WHERE Phrase='Mr Charlie's dog's dog and Mrs Molly's cat's cat plus Chris' bicycle' AND Item='wood';
I use Microsoft SQL
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>
Rather than composing a query as a string, write a parameterised query and supply whatever string as the parameter.
You don't say what sql library you use, but it'd look something like this
void prepare_find(pqxx::connection_base &c)
{
c.prepare(
"find",
"SELECT * FROM MyTable WHERE Phrase = $1 AND Item = $2");
}
pqxx::result execute_find(
pqxx::transaction_base &t, std::string phrase, std::string item)
{
return t.exec_prepared("find", phrase, item);
}
Related
For example my inquiry(question?) in SQL is:
SELECT * from COMPANY where imie="John",surname="Wattson",age=31;
I use sqlite3_exec where one of the arguments is callback. I don't know if this record is in my table, and would like to know it using sqlite_exec.
What should I do?
Sorry for my English. :(
If you just want to see if a record exists in the table, then you could do it with sqlite3_exec() using a callback function like this:
int myCallback(void *pUser, int argc, char **colData, char **colNames) {
int *flag = (int*)pUser;
*flag = 1;
return 1;
}
This works because if there are no records matching the query, then the callback function is not called. By returning 1 instead of 0, we are telling SQLite that we don't want any more rows from the query results.
Then, in the function where you are making the db query:
std::string sql = "SELECT * FROM COMPANY WHERE imie='John' AND surname='Wattson' AND age=31;";
char *pSql = sql.c_str(); // char*'s are better for talking to SQLite, and prior to C++14,
// a std::string is not guaranteed to be sequential in memory,
// so 'sql[0]' may not work right
char *pError = NULL;
int fHasResult = 0;
// db is an already-opened sqlite3*
int result = sqlite3_exec(db, pSql, myCallback, &fHasResult, &pError);
if (result) {
cout<<"Error was: "<<pError;
free(pError);
}
if (fHasResult) {
cout<<"The row exists in the database.";
}
else {
cout<<"The row does not exist in the database.";
}
You could use EXISTS, your query should then look something like this;
SELECT EXISTS (SELECT * FROM COMPANY WHERE imie="John" AND surname="Wattson" AND age=31);
For another example you could take a look at this;
Valid query to check if row exists in SQLite3
Using the mongocxx driver, I need to query mongodb for documents (of stock data) that fall within a certain date range.
Consider the following document format:
{
date : ISODate("2010-01-01T00:00:00Z"),
open : 12.00,
high : 13.00,
low : 11.00,
close : 12.50,
volume : 100000
}
Say I have one collection per stock, and hundreds of these documents per collection, each with a different date.
If a user supplies two dates formatted as strings (yyyy-mm-dd):
std::string start_date = "2010-01-01";
std::string end_date = "2010-02-05";
How can I query mongo to get all the files with dates between "start_date" and "end_date", (inclusive)?
Note: I am using mongodb 3.2.12, mongocxx driver version 3.0.2
Thanks,
Unfortunately, there doesn't seem to be a way to parse dates from strings with arbitrary timezones; all dates parse are assumed to be in the user's locale, which means you'll need to provide an offset to be able to correctly query the UTC dates stored in the database. Ideally these could be generated when the user provides a string, but this will obviously depend on the nature of your application.
Once you have the offset and the date string, std::get_time will get you most of the way there. After that, you just need to convert the std::tm to a type that you can construct a bsoncxx::types::b_date from and then query as usual. Here's some sample code that does the job:
#include <chrono>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/builder/basic/sub_document.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/types.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
bsoncxx::types::b_date read_date(const std::string& date,
std::int32_t offset_from_utc) {
std::tm utc_tm{};
std::istringstream ss{date};
// Read time into std::tm.
ss >> std::get_time(&utc_tm, "%Y-%m-%d");
// Convert std::tm to std::time_t.
std::time_t utc_time = std::mktime(&utc_tm);
// Convert std::time_t std::chrono::systemclock::time_point.
std::chrono::system_clock::time_point time_point =
std::chrono::system_clock::from_time_t(utc_time);
return bsoncxx::types::b_date{time_point +
std::chrono::hours{offset_from_utc}};
}
int main() {
// User inputs
std::string start_date = "2010-01-01";
std::string end_date = "2010-02-05";
std::int32_t offset_from_utc = -5;
// Code to execute query
mongocxx::client client{mongocxx::uri{}};
mongocxx::collection coll = client["db_name"]["coll_name"];
bsoncxx::builder::basic::document filter;
filter.append(bsoncxx::builder::basic::kvp(
"date", [start_date, end_date,
offset_from_utc](bsoncxx::builder::basic::sub_document sd) {
sd.append(bsoncxx::builder::basic::kvp(
"$gte", read_date(start_date, offset_from_utc)));
sd.append(bsoncxx::builder::basic::kvp(
"$lte", read_date(end_date, offset_from_utc)));
}));
for (auto&& result : coll.find(filter.view())) {
std::cout << bsoncxx::to_json(result) << std::endl;
}
}
I want use C++ regex class to turn
SELECT TableOne.ColumnOne, TableOne.#ColumnTwo, TableOne.ColumnThree FROM TableOne WHERE TableOne.#ColumnTwo ='abc'
into
SELECT TableOne.ColumnOne, TableOne.ColumnThree FROM TableOne WHERE TableOne.ColumnTwo ='abc'
basically, want to do the following
(1)remove anything like "TableOne.#ColumnTwo" before "FROM"
(2)remove any "#" after "FROM"
could someone please shed me some light? there does not seem a direct two to do all these in on go.
Description
Regex: ^(.*?)TableOne[.]#ColumnTwo,\s+(.*?)[#](.*?)$ Replace with: \1\2\3
Example
This is C# example is added to show how the regex works.
using System;
using System.Text.RegularExpressions;
namespace myapp
{
class Class1
{
static void Main(string[] args)
{
String sourcestring = "SELECT TableOne.ColumnOne, TableOne.#ColumnTwo, TableOne.ColumnThree FROM TableOne WHERE TableOne.#ColumnTwo ='abc'";
String matchpattern = #"^(.*?)TableOne[.]#ColumnTwo,\s+(.*?)[#](.*?)$";
String replacementpattern = #"\1\2\3";
Console.WriteLine(Regex.Replace(sourcestring,matchpattern,replacementpattern,RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline));
}
}
}
$sourcestring after replacement:
SELECT TableOne.ColumnOne, TableOne.ColumnThree FROM TableOne WHERE TableOne.ColumnTwo ='abc'
I was wondering if there is something I can use in C++ similar to "sqlparse" module in Python to format my query. Do you know what can I use?
I'm sorry for didn't provide an example before.
I want that something like this:
SELECT MEMB.NAME, MEMB.AGE, AGE.GROUP FROM MEMB, AGE WHERE MEMB.AGE = AGE.AGE
Become this:
SELECT MEMB.NAME,
MEMB.AGE,
AGE.GROUP
FROM MEMB,
AGE
WHERE MEMB.AGE = AGE.AGE
Thanks a lot.
You can write your own pretty printer. In that case, it won't be any hard. Just replace things like the following:
"FROM" -> "\nFROM"
"WHERE" -> "\nWHERE"
"," -> ",\n\t"
"AND" -> "AND\n\t"
"OR" -> "OR\n\t"
etc.
Edit: as you don't code, here's a little version of this functionality.
#include <string>
using std::string; /* put these lines in the top of your file */
string replace(string a, string b, string c) {
unsigned x;
for(x = a.find(b); x != string::npos;) {
a.erase(x, b.length());
a.insert(x, c);
}
return a;
}
string formatSQL(string sql) {
replace(sql, "FROM", "\nFROM");
replace(sql, "WHERE", "\nWHERE");
replace(sql, "," , ",\n\t");
replace(sql, "AND", "AND\n\t");
replace(sql, "OR", "OR\n\t");
}
So calling formatSql("SELECT MEMB.NAME, MEMB.AGE, AGE.GROUP FROM MEMB, AGE WHERE MEMB.AGE = AGE.AGE") gives you the desired result.
Suppose I have a structure in C or C++, such as:
struct ConfigurableElement {
int ID;
char* strName;
long prop1;
long prop2;
...
};
I would like to load/save it to/from the following XML element:
<ConfigurableElement ID="1" strName="namedElem" prop1="2" prop2="3" ... />
Such a mapping can be trivially done in Java/C# or any other language with run-time reflection for the matter. Can it be done in any non-tedious way in C++ with macros/template trickery?
Bonus points for handling nested structures/unions.
The technique you want is called serialization. You may want to read these articles:
http://www.codeproject.com/KB/cpp/xmlserialization.aspx
http://www.codesynthesis.com/products/xsd/ <=== Very close to what you want!
http://www.artima.com/cppsource/xml_data_binding.html
http://www.ibm.com/developerworks/xml/library/x-serial.html
http://www.firstobject.com/xml-serialization-in-c++.htm
EDIT:
There is another option for you: Xmlize provided by Ultimatepp:
http://www.ultimatepp.org/reference$Xmlize.html
http://www.ultimatepp.org/reference$Xmlize$en-us.html
http://www.ultimatepp.org/reference$XmlizeCustomValue$en-us.html
http://www.ultimatepp.org/reference$Xmlize_std$en-us.html
http://www.ultimatepp.org/reference$XML$en-us.html
Tips and tricks always exists. Take a look at Metaresc library https://github.com/alexanderchuranov/Metaresc
It provides interface for types declaration that will also generate meta-data for the type. Based on meta-data you can easily serialize/deserialize objects of any complexity. Out of the box you can serialize/deserialize XML, JSON, XDR, Lisp-like notation, C-init notation.
Here is a simple example:
#include <stdio.h>
#include <stdlib.h>
#include "metaresc.h"
TYPEDEF_STRUCT (host_t,
(char *, host),
int port,
);
TYPEDEF_STRUCT (config_t,
(host_t, local),
(host_t, remote),
(char *, name),
);
int main (int argc, char * argv[])
{
config_t config = {
.local = {
.host = "localhost",
.port = 8080,
},
.remote = {
.host = "google.com",
.port = 80,
},
.name = "service",
};
char * str = MR_SAVE_XML (config_t, &config);
if (str)
{
printf ("%s\n", str);
free (str);
}
return (EXIT_SUCCESS);
}
This program will output
$ ./config
<?xml version="1.0"?>
<config>
<local>
<host>localhost</host>
<port>8080</port>
</local>
<remote>
<host>google.com</host>
<port>80</port>
</remote>
<name>service</name>
</config>
Library works fine for latest gcc and clang.