"My question is about react-native sqlite-expo"
I’m using expo-sqlite for implementing a local database on a android app.
How to perform sqlite rollback transaction with expo library or is there any other component?I try to do transaction with this code :
const Deletequery = DELETE FROM Talukalist;
const InsertQuery = INSERT into Talukalist(State_Code, District_Code, Taluka_Code, Taluka_Name) VALUES ${string};
const SeleteQuery = SELECT * FROM Talukalist;
db.transaction(
function (tx) {
tx.executeSql(
Deletequery,
,
(tx, results) => {
console.log(“TalukaDelete query result callback”);
},
(tx1, error) => {
console.log(“TalukaDelete query Error callback”, error.message);
return true;
}
);
tx.executeSql(
InsertQuery,
,
(tx, results) => {
console.log(“TalukaInsert query result callback”);
},
(tx1, error) => {
console.log(“TalukaInsert query Error callback”, error.message);
return true;
}
);
},
(error) => {
console.log("DB Transaction Error Message :- ", error.message);
return true;
},
() => {
//console.log(“Success”);
db.transaction(function (tx) {
tx.executeSql(SeleteQuery, , (tx, results) => {
console.log(“DB Transaction Select query Success callback”);
});
});
}
);
Before any error i have 6 records in my table and it works properly with success callback.
Here is the output of first trancation :
TalukaDelete query result callback
TalukaInsert query result callback
DB Transaction Success callback result Array [
Object {
“COUNT(*)”: 6,
},
]
After success of one transaction i have tried to put error in my query and check it works proper or not.
It gives me such kind of output :
TalukaDelete query result callback
TalukaInsert query Error callback near “,”: syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT into Taluka,list(State_Code, District_Code, Taluka_Code, Taluka_Name) VALUES (‘6’,‘63’,‘393’,‘Adampur’),(‘6’,‘65’,‘6409’,‘Alewa’),(‘6’,‘58’,‘359’,‘Ambala’),(‘6’,‘58’,‘6406’,‘Ambala Cantonment’),(‘6’,‘67’,‘373’,‘Assandh’),(‘6’,‘69’,‘6457’,‘Ateli’)
DB Transaction Delete callback result near “,”: syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT into Taluka,list(State_Code, District_Code, Taluka_Code, Taluka_Name) VALUES (‘6’,‘63’,‘393’,‘Adampur’),(‘6’,‘65’,‘6409’,‘Alewa’),(‘6’,‘58’,‘359’,‘Ambala’),(‘6’,‘58’,‘6406’,‘Ambala Cantonment’),(‘6’,‘67’,‘373’,‘Assandh’),(‘6’,‘69’,‘6457’,‘Ateli’)
DB Transaction Error callback result Array [
Object {
“COUNT(*)”: 0,
},
]
So in my second trancation gives me error, even though my first transaction is work successfully and remove all the records and rollback transaction went failed. Please help me in this and share your answer with me.
Related
I am really new to Snowflakes. I am using Node Js drive to query Snowflakes database and for that I am using NODE PACKAGE https://www.npmjs.com/package/snowflake-sdk package. I successfully manage to connect my local server to snowflakes. When I query sqlText: select * from Test.deliverydb', I can see all my datas in console rows`.
In my Snowflakes dashboard I am passing conditional value and getting selected value. This is how I did it in my dashboard and getting expected result.
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE
online_store_transaction_id = '39485727'
I would like to this same query in Code. I am having hard time to understand snowflakes' documentation to implement above dashboard logic to my code.
I would like query my data around template string where user will put hardcode value and it will return the data. When I run this below query "Failed to execute statement due to the following error: Numeric value".Because of this where condition WHERE online_store_transaction_id = ${168141924}
const sql = `
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE online_store_transaction_id = ${168141924}
`;
connection.execute({
sqlText: sql,
fetchAsString: ['Number'],
complete: function (err, stmt, rows) {
if (err) {
console.error('Failed to execute statement due to the following error: ' + err.message);
} else {
if (!rows) {
throw new Error("Data not found");
}
console.log('Successfully executed statement: ' + stmt.getSqlText());
let data = {}
rows.forEach(test => data = test);
console.log({ data });
}
}
});
If I query like this this it works:
const sql = `
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE online_store_transaction_id = '168141924'
`;
connection.execute({
sqlText: sql,
fetchAsString: ['Number'],
complete: function (err, stmt, rows) {
if (err) {
console.error('Failed to execute statement due to the following error: ' + err.message);
} else {
if (!rows) {
throw new Error("Data not found");
}
console.log('Successfully executed statement: ' + stmt.getSqlText());
let data = {}
rows.forEach(test => data = test);
console.log({ data });
}
}
});
Since the online_store_transaction_id is not a numeric column, you need to add quotes around your value, as you did in your first example:
const sql = `
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE online_store_transaction_id = '${168141924}'
`;
I am having problems with saving JSON objects in the database using parameterized queries. I am using postman to send this object on red.body
enter image description here
On my server side I havet his code:
queryController.createQuery = (req, res, next) => {
const { info }= req.body;
const sqlQuery = 'INSERT INTO test (info) VALUES ($1) RETURNING *';
db.query(sqlQuery, [info])
.then(result => {
console.log(result);
if (result) res.locals.message = "Saved the query successfully";
next();
})
.catch(err => {
return next({
log: `queryController.createQuery: ERROR: ${typeof err === 'object' ? JSON.stringify(err) : err}`,
message: { err: 'Error occurred in queryController.createQuery. Check server log for more details.'},
})
})
Why is that I still get this error: enter image description here
throw new TypeError('Client was passed a null or undefined query')
^
TypeError: Client was passed a null or undefined query
Here is my table schema:
CREATE TABLE test (
id serial NOT NULL PRIMARY KEY,
info json NOT NULL
);
How do I format $1 correctly to get it accept it as JSON file?
Query example:
EXECUTE 'INSERT INTO test (info) VALUES ($1) RETURNING *' USING '[{"size": "Small", "quantity": 1, "product_id": 1}]'::jsonb;
I have a SQLite database I am trying to add data to with the sqlite3 package. My query is as follows, and works in the SQLite command line.
'INSERT INTO `EVENTS`(`ID`,`EventName`,`EventSociety`,`BookerName`,`BookerEmail`,`BookerStudentID`,`BookerPhone`,`TimeStart`,`TimeEnd`,`EquipmentList`,`EventSearchYear`,`EventSearchMonth`,`EventSearchDay`) VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);';
And I'm using this code to insert to the database in node.
db.run("begin transaction");
let sql = 'INSERT INTO `EVENTS`(`ID`,`EventName`,`EventSociety`,`BookerName`,`BookerEmail`,`BookerStudentID`,`BookerPhone`,`TimeStart`,`TimeEnd`,`EquipmentList`,`EventSearchYear`,`EventSearchMonth`,`EventSearchDay`) VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);';
console.log(sql);
db.run(sql,(err) => {
res.send('ok');
});
db.run("commit");
Trying this in node hard crashes, with a Illegal instruction: 4. However, it is only happening on two tables, both with over 5 fields, in my database, and not any other smaller ones. Is there a character limit I'm unaware of?
To avoid crash, we need to handle error as below:
Example
The line db.run(sql, params, function (err) { in below example:
let sql = `INSERT INTO Users(id,firstName,lastName,email,password,permissionLevel) VALUES (?,?,?, ?,?,?)`;
let params = [uuid4(), "fn1", "ln1", "a#a2.com", "pwd1", 0];
db.run(sql, params, function (err) {
if (err) {
console.error("Error: Insert failed: ", err.message);
console.error("Error: Full error: ", err);
return;
}
console.log("insert success");
});
I have a function that drops a table in a sqlite database in a expo react native project. When the table exists in the database the console.log statement prints table dropped. But if I run that same function twice in a row, Im expecting it to say no results because it was already dropped previously, but nothing prints on the console.
Why is that? And how do I fix this? I wish to know if sqlite transactions fail.
db.transaction(tx => {
tx.executeSql(
'DROP TABLE tableName;',
[],
(tx, results) => {
if (results && results.rows && results.rows._array) {
/* do something with the items */
// results.rows._array holds all the results.
console.log(JSON.stringify(results.rows._array));
console.log('table dropped')
}else{
console.log('no results')
}
}
)
});
Trying to drop a table that doesn't exist causes an error. You only have a success callback, you need an error callback as well.
db.transaction(tx => {
tx.executeSql(
'DROP TABLE tableName;', [],
(tx, results) => {
if (results && results.rows && results.rows._array) {
/* do something with the items */
// results.rows._array holds all the results.
console.log(JSON.stringify(results.rows._array));
console.log('table dropped')
} else {
console.log('no results')
}
},
(tx, error) => {
console.log(error);
}
)
});
I have an API running in AWS Lambda written on Node.JS (6.10.3), using the npm package mysql (2.13.0). This is deployed and managed using Serverless.
I am Inserting a single row into a table on a MariaDB RDS instance using the following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
"host": process.env.CONFIG_HOST,
"user": process.env.CONFIG_WRITE_USER,
"password": process.env.CONFIG_WRITE_PW,
"database": process.env.CONFIG_DB,
"connectionLimit": 1
});
module.exports.post = (event, context, callback) => {
var body = JSON.parse(event.body);
var params = event.someParameter;
var sql = getSql(body.name);
console.log(sql);
connection.query(sql, onQueryComplete(params, callback));
}
const onQueryComplete = function(params, callback) {
return function(error, result) {
if (error) {
console.log(error);
callback(null, 'some error response');
}
// do something else...
}
}
function getSql(name) {
return `
INSERT INTO lds_config.test_table
(
name,
name_hash
)
VALUES
(
'${name}',
MD5('${name}')
);`;
}
If I check the table, I can see that the insert has completed successfully and the new row has been added, however error is being set - meaning something has gone wrong somewhere (possibly after the insert).
The error returned by mysql (in console.log) is:
{
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'HANDLER RESOLVED _____');
// Timeout clearing if needed
' at line 2
at Query.Sequence._packetToError (...\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
at Query.ErrorPacket <<stack trace continues>>)
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0
}
This is followed by a second error, stating that callback is not a function:
Debug: internal, implementation, error
TypeError: Uncaught error: callback is not a function
Similar code is working elsewhere in the API for selects. Thanks!
Further notes:
The table is:
CREATE TABLE lds_config.test_table(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(500), name_hash CHAR(32));
The result from console.log(sql); is:
INSERT INTO lds_config.test_table
(
name,
name_hash
)
VALUES
(
'test01',
MD5('test01')
);
Which works when I run it directly in mysql workbench.
Include the query also since the first error is regarding MySQL syntax. About callback is not a function it is not passed as a parameter in below code as far as I see.
const onQueryComplete = function(params) {
return function(error, result, callback) {
if (error) {
console.log(error);
callback(null, 'some error response');
}
// do something else...
}
}
Above is the corrected one.