How to get detailed error msg from monetdbe_query - sql

Looking at the C examples for monetdbe_query in the GitHub repository: https://github.com/MonetDBSolutions/monetdbe-examples
The prescribed way to run queries is to run SQL queries in an IF statement that captures Null return values as shown below:
if (monetdbe_query(db, "SELECT * FROM mystrings", &result, NULL) != NULL) {
fprintf(stderr, "Failed to run select query\n");
goto cleanup;
}
is it possible to get any detailed information regarding why the SQL statement failed?

Many monetdbe_ functions return an error message if something went wrong, or NULL otherwise. So, just catch the return value. See the example copy_into.c in monetdbe-examples:
if((err=monetdbe_query(db, sql, NULL, NULL)) != NULL) {
printf("%s\r\n", err);
return -1;
}
grep for err in the examples for more.

Related

Golang SQL error expected 0 arguments got 3

I'm using github.com/denisenkom/go-mssqldb library and driver but getting an error sql: expected 0 arguments, got 3 exit status 1 when inserting new row.
tsql := "INSERT INTO Uploads (Fname, Fsize, Ftype) VALUES (#Fname, #Fsize, #Ftype );"
fmt.Printf("tsql = %s\n", tsql)
//Execute non-query with named parameters
res, err := db.ExecContext(
ctx,
tsql,
sql.Named("Fname", fname),
sql.Named("Fsize", fsize),
sql.Named("Ftype", ftype))
if err != nil {
log.Fatal(" AddRow_v1() -> Error creating new row: " + err.Error())
return -1, err
}
This issue might be related to driver name used in the connection string.
I've tried the same query with yours, the record is created without any errors.
I believe that you are currently using mssql in connection string; sql.Open("mssql", conn) (This issue has already been discussed in https://github.com/denisenkom/go-mssqldb/issues/594#issuecomment-809922317)
If you try again by replacing "mssql" to "sqlserver", the problem should be solved.

sqlite_exec for insert query is successful, but entry not found in sqlite table

I'm facing a strange issue where in my insert query using sqlite_exec API says successful return value, but when I check in sqlite table I dont see that entry, Below is my code
Insert query : INSERT INTO table_name VALUES (0,1584633967816,1584634000,'dasdasda','1584634000','28641','dasdas','dsadas','dsadsa','/rewrwe','rwerewr','rewrewr','0',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)
sqlite_exec code block:
sqliteError = sqlite3_exec(pSqlHandle, oSqlQuery.str().c_str(), NULL, NULL, NULL);
if (sqliteError == SQLITE_OK)
{
LOG(DbgLogger, LOG_LEVEL_DEBUG, "Query %s successful\n",
oSqlQuery.str().c_str());
if (pSqlHandle) {
sqliteError = sqlite3_close(pSqlHandle);
if (sqliteError != SQLITE_OK) {
sqlRet = SQL_API_FAILURE;
}
else {
pSqlHandle = NULL;
}
}
sqlRet = SQL_API_SUCCESS;
if (m_useLockFile) {
//write done, release write lock
sqlRet = releaseWriteLock();
/* reset write lock file name */
bWriteLckAvailable = false;
}
break;
}
I can see print "LOG(DbgLogger, LOG_LEVEL_DEBUG, "Query %s successful\n",)"
But when I do a select from command line on the I dont see any entry as such
eg: select * from table_name where column_name=1584633967816;
Anyone faced similar issue ?

How do I insert a row into an SQLite database using swift?

I have a SQLITE3 database with two tables, main and activities. I am trying to insert a row into the main table just to check it works, using the sql command on terminal I am able to insert, but not through swift. The database is connected and allows me to read from the database using swift but not write to it.
let insertStatementString = "INSERT INTO main (DATE) VALUES (?);"
func insert() {
var insertStatement: OpaquePointer?
//1
if sqlite3_prepare_v2(mySQLDB,insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {
let date: NSString = "14071999"
sqlite3_bind_text(insertStatement,1,date.utf8String, -1, nil)
if sqlite3_step(insertStatement) == SQLITE_DONE {
print("\nSuccessfully inserted row")
} else
{ print("\nCould not insert a row")
}
}
else
{ print("\nInsert statement not prepared")
}
sqlite3_finalize(insertStatement)
}
When the program reaches 'if sqlite3_step(insertStatement) == SQLITE_DONE' it then skips to 'Could not insert row'.
Can anyone see why this is going wrong?
If your insert failed, you should print the error message, sqlite3_errmsg, which will tell you precisely what went wrong.
FWIW, your code worked for me, so it’s probably something not included in your question, for example how you opened the database and/or how the table was defined. Possible problems include:
inserting into a read-only database (e.g., opened database in the bundle which is read-only, explicitly opened with sqlite3_open_v2 in read-only mode, etc.);
your bind statement failed (you really should check for success there, too);
having a unique key on this column and already having this value somewhere; or
having other required (NOT NULL) columns that were not supplied.
Regardless, logging the error message will remove any ambiguity.
E.g.
func insert() {
var insertStatement: OpaquePointer?
guard sqlite3_prepare_v2(mySQLDB, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK else {
printError(with: "INSERT statement not prepared")
return
}
defer { sqlite3_finalize(insertStatement) }
let date = "14071999"
guard sqlite3_bind_text(insertStatement, 1, date.cString(using: .utf8), -1, SQLITE_TRANSIENT) == SQLITE_OK else {
printError(with: "Bind for INSERT failed")
return
}
guard sqlite3_step(insertStatement) == SQLITE_DONE else {
printError(with: "Could not insert a row")
return
}
print("Successfully inserted row")
}
func printError(with message: String) {
let errmsg = sqlite3_errmsg(mySQLDB).flatMap { String(cString: $0) } ?? "Unknown error"
print(message, errmsg)
}
Where
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
While I structured this with guard statements, even if you stay with your if pattern, make sure you only sqlite3_finalize if the prepare statement succeeded. There’s no point in finalizing if the prepare failed.
It’s also prudent to use SQLITE_TRANSIENT for bound parameters.

Why does this Linq Query Return Different Results than SQL Equivalent?

I'm sure I'm missing something simple but I have a linq query here:
public static List<Guid> GetAudience()
{
var createdOn = new DateTime(2018, 6, 30, 0, 0, 0);
var x = new List<Guid>();
try
{
var query = from acc in Account
where acc.num != null
&& acc.StateCode.Equals(0)
&& acc.CreatedOn < createdOn
select new
{
acc.Id
};
foreach (var z in query)
{
if (z.Id != null)
{
x.Add(z.Id.Value);
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return x;
}
I wanted to verify the count in SQL because it would only take a couple seconds so:
select count(*)
from Account a
where a.num is not null
and a.statecode = 0
and a.createdon < '2018-06-30 00:00:00'
And now the SQL query is returning 9,329 whereas Linq is returning 10,928. Why are my counts so far off when the queries are doing the same thing (so I thought)? What simple thing am I missing?
Thanks in advance--
Your method is returning a list of records where the Id values are not null (plus the other criteria). The SQL query is returning a count of the number of records (plus the other criteria). Without the definition of your table, it's hard to know whether that is significant.
Unrelated tip: it's not a good idea to catch and swallow exceptions like that - the caller of your method will have no idea that anything went wrong, so processing will continue; but it will be using incomplete data, potentially leading to other problems in your program later.

Getting Invalid number of parameters in Doctrine2 and Symfony Querybuilder

Here is my code
if(!$criteria){
return null;
}
$em = $this->doctrine->getEntityManagerForClass('Sample\MyBundle\Entity\Call');
$qb = $em->createQueryBuilder();
$qb->add('select', 'c')->add('from', 'Sample\MyBundle\Entity\Call c');
if($criteria->getReason() && $criteria->getReason() != null){
$qb->add('where', 'c.reason = ?1');
$qb->setParameter(1, $criteria->getReason());
}
if($criteria->getCallDate() && $criteria->getCallDate() != null){
$qb->add('where', 'c.callTime = ?2');
$qb->setParameter(2, $criteria->getCallDate());
}
if($criteria->getPage()>1){
$qb->setFirstResult(($criteria->getPage()-1) * 10)->setMaxResults(10);
}
$query = $qb->getQuery();
return $query->getResult();
I'm getting this error - Invalid parameter number: number of bound variables does not match number of tokens I googled but couldn't found a solution. Need help with this.
I even tried to put both setParameter() calls after conditional check if statements but that also give the same error. If I don't set the second parameter and remove second where condition then it works.
Oh, I guess I was making a mistake. I think I can not use multiple 'where' in 'add' function. I replaced it with $qb->andWhere('c.callTime > ?2'); and now it works fine.