How to insert a string containing '%' using QSqlQuery? - sqlite

I am trying to insert a string which contains '%' using QsqlQuery but I am always getting an error of type QSqlError::TransactionError with the message
"near "%": syntax error Unable to execute statement"
I have tried several ways to escape the "%" but I am still getting that error message. Please see the code snippet below.
query.exec(QString("INSERT INTO my_table (name, address) VALUES (\"%1\", \"%2\")")
.arg("Harry", "#302%%1,..."));
In place of "%%", I have tried "\%", "\%", but still it didn't work and I am having the same error message.

In SQL, strings are delimited with ', not ".
Anyway, you should use parameters:
query.prepare("INSERT INTO my_table (name, address) VALUES (?, ?)");
query.addBindValue("Harry");
query.addBindValue("#302%%1,...");
query.exec();

Related

Getting error with basic trim() function in U-SQL script

I want to apply .trim() function on a column but getting the error.
Sample data:
Product_ID,Product_Name
1, Office Supplies
2,Personal Care
I have to do some data manipulation but can't get the basic trim() function right.
#productlog =
EXTRACT Product_ID string,
Prduct_Name string
FROM "/Staging/Products.csv"
USING Extractors.Csv();
#output = Select Product_ID, Product_Name.trim() from #productlog;
OUTPUT #output
TO "/Output/Products.csv"
USING Outputters.Csv();
Error:
Activity U-SQL1 failed: Error Id: E_CSC_USER_SYNTAXERROR, Error Message: syntax error. Expected one of: '.' ALL ANTISEMIJOIN ANY AS BEGIN BROADCASTLEFT BROADCASTRIGHT CROSS DISTINCT EXCEPT FULL FULLCROSS GROUP HASH HAVING INDEXLOOKUP INNER INTERSECT JOIN LEFT LOOP MERGE ON OPTION ORDER OUTER OUTER UNION PAIR PIVOT PRESORT PRODUCE READONLY REQUIRED RIGHT SAMPLE SEMIJOIN SERIAL TO UNIFORM UNION UNIVERSE UNPIVOT USING WHERE WITH ';' '(' ')' ',' .
Try the below, afaik you need to alias trimmed fields
#productlog =
EXTRACT Product_ID string,
Prduct_Name string
FROM "/Staging/Products.csv"
USING Extractors.Csv();
#output = Select Product_ID, Product_Name.trim() as Trimmed_Product_Name from #productlog;
OUTPUT #output
TO "/Output/Products.csv"
USING Outputters.Csv();
Got it right finally, in case someone else face the same issue. U-SQL is more like C# so it will be a bit tricky for people like me, coming from pure SQL background.
Code:
#productlog =
EXTRACT Product_ID string,
Prduct_Name string
FROM "/Staging/Products.csv"
USING Extractors.Csv();
#output =
SELECT
T.Product_ID,
T.Prduct_Name.ToUpper().Trim() AS Prduct_Name
FROM #productlog AS T;
OUTPUT #output
TO "/Output/Products.csv"
USING Outputters.Csv();

R JDBC error "Unable to retrieve JDBC result set for insert into ..."

I am trying to write an R data.frame to a Netezza table. It has about 55K rows and I have set 4GB as memory limit for Java (options(java.parameters = "-Xmx4096m"))
Query:
insert into MY_TABLE_NAME select * from external 'csv_file_containing_data_frame.csv' using (delim ',' remotesource 'jdbc');
The above line of SQL works without any issues when I run it from a tool like DbVisualizer but I get the following error when I try to run it from RStudio.
R Code:
driver <- JDBC(driverClass="org.netezza.Driver", classPath = "drivers//nzjdbc.jar", "'")
connWrite <- dbConnect(driver, "jdbc:netezza://DB_SERVER:1234//DB_NAME", username, password)
str_insert_query <- paste(
"insert into MY_TABLE select * from external '", OutputFile , "' using (delim ',' remotesource 'jdbc');", sep = ""
dbSendQuery(connWrite, str_insert_query[1])
dbDisconnect(connWrite)
Error Message:
Error in .verify.JDBC.result(r, "Unable to retrieve JDBC result set for ", :
Unable to retrieve JDBC result set for insert into MY_TABLE select * from external 'C:/.../csv_file_containing_data_frame.csv' using (delim ',' remotesource 'jdbc'); (netezza.bad.query.result)
dbWriteTable works but is so slow that it cannot be used.
Tried to assign the result of dbSendQuery() to a variable but it
didn't work.
Any help will be greatly appreciated. Thank you!
Need to use dbSendUpdate.
dbSendUpdate(connWrite, str_insert_query[1])

How to use RowMapper to insert record into table?

How to insert data into table using row mapper?
I am trying this:
Employee user1 = jtemplate.queryForObject("INSERT INTO employee(id, name,salary) VALUES(10,'ABC',12333);",new BeanPropertyRowMapper<Employee>(Employee.class));
It gives me bad SQL grammar error.
But query works in SQL developer. What I am doing wrong?
Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [INSERT INTO employee(id, name,salary) VALUES(99,'ABC',12333)]; nested exception is java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:411)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:466)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:476)
at com.cts.orm.rowmapper.Test.main(Test.java:29)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:600)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Odscrarr.doODNY(T4C8Odscrarr.java:98)
at oracle.jdbc.driver.T4CStatement.doDescribe(T4CStatement.java:805)
at oracle.jdbc.driver.OracleStatement.describe(OracleStatement.java:3978)
at oracle.jdbc.driver.OracleResultSetMetaData.<init>(OracleResultSetMetaData.java:55)
at oracle.jdbc.driver.OracleResultSetImpl.getMetaData(OracleResultSetImpl.java:175)
at org.springframework.jdbc.core.BeanPropertyRowMapper.mapRow(BeanPropertyRowMapper.java:240)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:455)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:400)
... 3 more
NamedParameterJdbcTemplate does what you want:
namedParameterJdbcTemplate.update(
"INSERT INTO employee(id, name, salary) VALUES (:id, :name, :salary)",
new BeanPropertySqlParameterSource(Employee.class));
removing the semi colon at the end of the statement should solve the problem use it like this. when using the jdbc templates it is not good to use semicolon at the end of sql statements
Employee user1 = jtemplate.queryForObject("INSERT INTO employee(id, name,salary) VALUES(10,'ABC',12333)",new BeanPropertyRowMapper<Employee>(Employee.class));
try using it like
jtemplate.update("INSERT INTO Employee(ID, NAME, Salary) VALUES (?, ?, ?)",
new Object[] { employee.getId(), employee.getName(), employee.getSalary() });
i am using this and it works correctly and displays no errors
Try this:
jdbcTemplate.update("INSERT INTO employee(id, name,salary) VALUES(?,?,?)", 10, "ABC", 12333);

SQLite3 - Wrong data stored

I got trouble with some data which get's wrong in that Database.
Trying to store a Lua String, for example:
foo = "1234..78.0"
The database returns no error. But reading the string from the SQLite 3 Database, it returns strange values, alwas with a "-" as first digit.
The Database:
db:exec( "CREATE TABLE IF NOT EXISTS "
"Pattern("
"Idx INTEGER PRIMARY KEY AUTOINCREMENT,"
"Strip TEXT,"
"Startdigit INTEGER,"
"Enddigit INTEGER,"
"Value TEXT," -- < -- THIS FIELD IS THE ISSUE
"Name TEXT,"
"Message TEXT,"
"Relatives BLOB"
")"
)
The write query:
queries.newPattern:prepare("INSERT INTO Pattern(Strip, Startdigit, Enddigit, Value, Name, Message, Relatives) VALUES( (?) , (?) , (?) , (?) , (?) , (?) , (?) )")
Where (?) are variables which have to be bound before executing the query by:
queries.newPattern:bind( idx , value ) -- binds value to (?) at (idx)th position
All Datatypes are correct, and the execution does not return any error.
err, errno = queries.newPattern:exec()
So err and errno are nil.
queries.newPattern:lastError()
returns nil.
Reading the Database with:
db:exec("SELECT * FROM Pattern")
Returns all data correct, except the "Value" field, which gets corrupted.
After every query, SQLites last Error is nil, so I assume there are no datatype mismatches or something.
The return value is something like(example):
"-1434302411"
What black magic is performing here?

Sqlite DB Error - could not prepare statement

I am getting following error on insert statement for sqlite DB
could not prepare statement (1 near "undefined": syntax error)
I tried 2 variations of insert, for both error is same
var sql = "INSERT INTO Med(MedID) VALUES(?),";
sql += "['"+dataObj[i].MedID+"']";
var sql = "INSERT INTO Med(MedID) VALUES ('"+dataObj[i].MedID+"')";
tx.executeSql(sql);
The correct way to give parameters to an SQL statement is as follows:
var sql = "INSERT INTO Med(MedID) VALUES (?)";
tx.executeSql(sql, [dataObj[i].MedID]);
It looks like you are missing the space that is needed between the table name and the column names.
Try this:
var sql = "INSERT INTO Med (MedID) VALUES ('"+dataObj[i].MedID+"')";
tx.executeSql(sql);
Make sure your dataObj[i].MedID is also defined. Add a console.log(sql) before your executeSql statement to check the command before using it.

Resources