I need to make an insert query in mssql but I can't come around how to parse the values that come from an object to the query. I have this so far. I'm using a string builder, I put what the outcome of query is in the commented part
form = {x:'value1', y:'value2', z:'value3'}
return new Promise(
(resolve, reject) => {
var query = calculation.insert(form).toQuery();
//query.text value will be: 'INSERT INTO [table] ([x], [y], [z]) VALUES (#1, #2, #3)'
//query.values will be ['value1', 'value2', 'value3']
new sql.Request().input('values', sql.VarChar, query.values).query(query.text).then(result => {
return { completed: true }
}).catch(err => {
throw err;
{ completed: false };
})
}
)
But this is not working. I can't figure how to parse the query.values properly to the query. Can anyone help? Thanks
Related
I am asking this , because sometimes(rarely) my query doing multiple additions.
I am opening db every page at the top.
var db = SQLite.openDatabase({name:'appdb.db',createFromLocation: '~appdb.db'})
my query is
db.transaction((tx) => {
tx.executeSql('INSERT INTO messages (chatID,messageID,senderID,message,uri,type,date)'+
'values(?,?,?,?,?,?,?)',[this.state.chatID,data.messageID,data.senderID,data.message,data.uri,data.type,data.date], (tx, results) => {
});
});
I think about convert to this for every query
import db from '../Classes/db';
db.open();
db.transaction((tx) => {
tx.executeSql('INSERT INTO messages (chatID,messageID,senderID,message,uri,type,date)'+
'values(?,?,?,?,?,?,?)',[this.state.chatID,data.messageID,data.senderID,data.message,data.uri,data.type,data.date], (tx, results) => {
});
});
db.close();
I have a SQL Server stored procedure to create a new user which I call from my Nodejs code. All works fine and the record is created but I want to be able to check if it really was inserted and was hoping to use the rowsAffected but that always comes back as [] the result from my insert is
{
"recordsets": [],
"output": {},
"rowsAffected": [],
"returnValue": 0
}
If I call the procedure from SQL Server Management Studio, I get the affected rows of 1. So am I missing something?
Here is code of how I call the stored procedure:
let storedProcedure = async (params, storedProcedureName) => {
const pool = await getOrCreatePool()
let request = await pool.request()
params.forEach((parameter) => {
parameterDirection = parameter.isOutput ? 'output' : 'input';
request = request[parameterDirection](parameter.name, parameter.type, parameter.value)
});
try {
return await request.execute(storedProcedureName)
} catch(err) {
console.error('StoredProcedure error', err);
return null;
}
}
I am working with the database in ionic, I call one API that returns me a number of records, I have to insert those records into the database and when to insert operations are completed then I want to call select records from the database. problem is asynchronous behavior, the select records from the database called before the insert operations are completed. can anyone help me to resolve this? my code is below...
DbProvider:
export class DbProvider {
public addData(dId: string, sId: string, subId: string, subName: string,
dDate: string, cId: string, cName: string, stdId: string, stdName: string,
) {
return new Promise((resolve, reject) => {
this.db.executeSql("INSERT INTO data (dId , sId , subId , subName ," +
" dDate , cId , cName , stdId , stdName ) VALUES (?, ?,?, ?,?, ?,?, ?,?)",
[dId, sId, subId, subName, dDate, cId, cName, stdId, stdName]).then((data) => {
resolve(data);
}, (error) => {
reject(error.tostring());
});
});
}
}
database insert and call
for (let temp of ApiData) {
this.DbHandler.IsAvailable(temp.dId).then(data => {
if (data) {
console.log("did Available editing " + data);
this.DbHandler.editData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName);
} else {
console.log("did not Available inserting " + data);
this.DbHandler.addData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName);
}
});
}
this.getDataFromDb();
I have multiple INSERTs I'd like to be done before starting SELECT requests. My problem is that the INSERT is not yet finished when the SELECT fires.
Call read from DB in then method:
let promises = [];
for (let temp of ApiData) {
let promise = new Promise((resolve, reject) => {
this.DbHandler.IsAvailable(temp.dId).then(data => {
if (data) {
console.log("did Available editing " + data);
this.DbHandler.editData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName).then(() => resolve());
} else {
console.log("did not Available inserting " + data);
this.DbHandler.addData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName).then(() => resolve());
}
});
};
promises.push(promise);
}
Promise.all(promises).then(() => this.getDataFromDb());
I have a NodeJS application which is my server and I created a Database class to help me handle querying my SQL DB. If I send requests a second between each other, everything runs fine.. no problems.. But if I start spamming requests to my server it crashes due to Error: Cannot enqueue Quit after invoking quit.
Here's my query function inside my Database class
static query(query: string): Promise<any> {
console.log('Query: ' + query);
return new Promise((resolve, reject) => {
this.connect().then(success => {
sqlConn.query(query, (err, results) => {
if (err) { return reject(err);
} else {
return resolve(results);
}
});
}).catch(err => {
return reject(err);
}).then( () => {
if (sqlConn.state !== 'disconnected') {
sqlConn.end();
}
});
});
};
and here's the this.connect() function
static connect(): Promise<any> {
return new Promise((resolve, reject) => {
sqlConn = mysql.createConnection(this.connectionData);
sqlConn.connect(err => {
if (err) { return reject(err); } else {
return resolve('SQL connection established');
}
});
});
};
I'm pretty sure the problem appears sometimes, it would still be
processing one query, and then another query comes before the first
one finishes, so it would call sqlConn.end() twice, even when it's
already disconnected? Any help is greatly appreciated...
> Main goal is for the query to wait till it's 100% done before it runs
the next one..
You can simplify your code by using the npm module mysql and use it's built-in connection pool.
From the documentation:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
You can, of course, create your own function that promisifies that call like this:
function query (sql) {
return new Promise((resolve, reject) => {
pool.query(sql, (error, results, fields) =>
error ? reject(error) : resolve({ results, fields });
};
}
If you really wants to use this approach then please use eachSeries function of async library.
var chunkedArray= [];
async.eachSeries(chunkedArray, startUpload, endUpload);
funtion startUpload(data,cb){
//iterate over every single item in array 1 at a time
}
function endUplaod(err){
//finally call this
}
This might help:-
https://caolan.github.io/async/docs.html#eachSeries
But i rather suggest you to use pooling of connection which make less overhead on your db and you can use your mysql more efficiently then making multiple connection.
// Load module
var mysql = require('mysql');
// Initialize pool
var pool = mysql.createPool({
connectionLimit : 10,
host : '127.0.0.1',
user : 'root',
password : 'root',
database : 'db_name',
debug : false
});
module.exports = pool;
So I am looking to model our existing redis data into aerospike. One requirement that we have is to be able to get all the keys for a given user. For eg., say we have keys such as <id>:<timestamp>. Now, at some point in time, I need to get all keys for the given id, where I would require something like a prefix search across all keys in the aerospike namespace (which are indexed) to get the values for all <id>:<timestamp> keys. Would like to know if this is possible, and if yes, how.
You cannot do a query on key prefix directly. The server only stores the key digest, so the key value (<id>:<timestamp> in your case) doesn't get indexed.
The way to model this would be to add the <id> part of your key as a separate record bin. Then you can index that bin and run a query on it.
Here is a simple example - it's using the Aerospike Node.js client but the concept is the same no matter what client you prefer:
const Aerospike = require('aerospike')
const ns = 'test'
const set = 'demo'
// connect to cluster and create index on 'id' bin
var client = Aerospike.client()
client.connect((err) => {
assertOk(err, 'connecting to cluster')
createIndex('id', 'id_idx', Aerospike.indexDataType.STRING, () => {
// create a new sample record
var userId = 'user1'
var ts = new Date().getTime()
var key = new Aerospike.Key(ns, set, `${userId}:${ts}`)
var record = { id: userId, value: Math.random() }
client.put(key, record, (err) => {
assertOk(err, 'write record')
// query for records with matching 'id'
var query = client.query(ns, set)
query.where(Aerospike.filter.equal('id', userId))
var stream = query.foreach()
stream.on('error', (error) => assertOk(error, 'executing query'))
stream.on('end', () => client.close())
stream.on('data', (record, meta, key) => {
console.log(record)
})
})
})
})
function assertOk (err, message) {
if (err) {
console.error('ERROR: %s - %s', message, err)
process.quit()
}
}
function createIndex (bin, name, datatype, callback) {
var index = {
ns: ns,
set: set,
bin: bin,
index: name,
datatype: datatype
}
client.createIndex(index, (err, job) => {
assertOk(err, 'creating index')
job.waitUntilDone(100, (err) => {
assertOk(err, 'creating index')
callback()
})
})
}
Hope this helps!