retrieve auto_incremented ID of first INSERT for second INSERT [duplicate] - javascript

This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 4 years ago.
I'm using JDBC and google app script.
I need to insert rows created via an HTML interface, only problem is that rows contain 2 inputs that are represented in different tables of my MYSQL database.
My second table has a foreign key that references the first table (product_id references id from table product).
Here are my tables
product:
id, name
product_quantity:
id, product_id, quantity
Here is what I would like to achieve in pseudo-code:
function update(row){
insertProductSQL = "INSERT INTO products (name) VALUES (" + row.name + ")";
insertProductQuantity = "INSERT INTO products_quantity (product_id, quantity) VALUES (" + /*HERE IS THE PROBLEM*/ + ", " + row.quantity + ")"
var conn = getConnection(); //JDBC connection object
var stmt = conn.createStatement();
stmt.executeQuery(insertProductSQL)
stmt = conn.createStatement();
stmt.executeQuery(insertProductQuantity);
conn.close();
}
So problem I'm facing is that I don't know if SQL or JDBC gives a simple way to retrieve the auto incremented value id created on the first insert to use it for my second insert.
Help is greatly appreciated, don't hesitate telling me if unclear to you.

Use the LAST_INSERT_ID() function.
insertProductQuantity = "INSERT INTO products_quantity (product_id, quantity) VALUES (LAST_INSERT_ID(), " + row.quantity + ")"

Related

Dynamic SQL using Snowflake SQL Stored Procedure

I want to be able to update rows of data in a set list of tables for certain columns within those tables.
Basically something like this;
TABLE_NAME COL1
TABLE1 NAME
TABLE2 ADDRESS
select * from TABLE1;
Aidan
Select * from TABLE2;
Ireland
So something like the query below as a stored procedure that would gather all the tables and columns to be altered and update the records accordingly.
update $TABLE_NAME set $COL1 ='*' where ID in (select ID FROM EXTERNAL_TABLE)
Any help greatly appreciated.
Tried messing around with this sample but got nowhere when I try build on it
CREATE OR REPLACE PROCEDURE DATA_MASKING("P_TABLE_NAME" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS '
// Define query String
var sql_command = "UPDATE " + P_TABLE_NAME + " SET IND_ADDR1 = NULL;"
//Prepare SQL statement
var stmt = snowflake.createStatement({sqlText: sql_command});
//Execute SQL Statement
var rs = stmt.execute();
return ''Table truncated successfully.''
';
call PERSISTENT_DATA_MASKING('TEST_TABLE');
The Proc you had given works. Just needs few amends which you must have been able to do. So, not sure what exactly is the question.
CREATE OR REPLACE PROCEDURE DATA_MASKING("P_TABLE_NAME" VARCHAR(16777216), "P_COLUMN_NAME" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS '
// Define query String
var sql_command = "UPDATE " + P_TABLE_NAME + " SET " + P_COLUMN_NAME + " = ''x'';"
//Prepare SQL statement
var stmt = snowflake.createStatement({sqlText: sql_command});
//Execute SQL Statement
var rs = stmt.execute();
return ''successful''
';
CALL DATA_MASKING('SCHEMA.TABLE_NAME','COLUMN_NAME');
SELECT * FROM SCHEMA.TABLE_NAME;

Sql dynamic query syntax error

This is my sql query
"select * from applicant where email =ABC.Com"
I want table name, colum name and value after where clause dynamic in form of variables there. Can you tell me the right syntax? I have tried this so far
"select * from " tableNameVariable+"where "columnNameVariable+"= "inputedEmailVariable
now this query is giving an error near =inputedEmailVariable.
Note : I want to use this string in nodejs function. Please tell me right syntax?
Try:
"select * from " + tableNameVariable + " where " + columnNameVariable + " = '" + inputedEmailVariable + "'"
You're missing some + operators, and also missing a space before where.
var sql = "select * from " + tableNameVariable + " where " + columnNameVariable + " = " + inputedEmailVariable
You should be very careful if the variables are coming from user input, since this can result in SQL injection. Make sure the variables contain table and column values that they're allowed to access.
And if you're compareing the column with a string, you'll need quotes around the string. But it would be better to use a placeholder at that point, rather than concatenating the variable.

Apostrophe breaking insert query in SQLite in Titanium [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I am writing an application in JavaScript using Appcelerator's Titanium development platform to deploy to the Android mobile platform. I am trying to perform an INSERT to an SQLite database.
The strings whenever they have a single quote or an apostrophe entered by a user breaks the insert query. What am I doing wrong?
var db = Ti.Database.install('db/kewGarden.sqlite', 'kewGarden');
var driveByData = {
"notes" : $.row3.getValue() // User entered string
};
driveByData = JSON.stringify(driveByData);
dbLib.saveRecording(saveDriveByDetailsSuccess, saveDriveByDetailsError, {
ref_id : newdriveById,
tableName : tableName,
data : driveByData
});
saveRecording : function(onSuccessCallback, onErrorCallback, options) {
var strReplaceData = options.data.replace("'", "\'");
db.execute("INSERT INTO g_temp (ref_id, table_name, data, site) VALUES (" + options.ref_id + ",'" + options.tableName + "','" + strReplaceData + "','" + options.site + "')");
},
The docs for this database are here:
http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Database.DB-method-execute
Use parameters, then you don't need to escape anything:
db.execute('INSERT INTO MyTable(ID, Name) VALUES(?, ?)', 123, name);
Your Query like this,
db.execute('INSERT INTO g_temp (ref_id, table_name, data, site) VALUES (?,?,?,?)',options.ref_id,options.tableName,options.data,options.site);

WebSQL: Error processing SQL: number of '?'s in statement string does not match argument count

I want to create a dynamic function to INSERT data into the webSQL Database. I cannot use indexed DB because Zetakey does not support it.
tx.executeSql("INSERT INTO " + table + "(" + formatfields + ")
VALUES (" + formatqm + ")",
[formatvalues],
webdb.onSuccess,
webdb.onError);
Ich übergebe an den Query:
formatfields = "one, two"; (up to an undefined number)
formatqm = "?, ?";
formatvalues = "123, 456"; (dynamic user entries for x fields)
Can someone tell me what do I have to do with the formatvalues? When I write 123, 456 directly its working fine.
Thanks in advance!
Instead of dynamically create or change table column fields, use JSON serialization of the record. Basically store stringify user given object data on INSERT and parse on retrieval. If you need query over column, initialize those columns only. It will be just like IndexedDB does.
/*array.push */
formatvalues = new Array;
formatvalues.push("123");
and so on!

Modify JavaScript Object and use setRowsData to write to individual cell

I am using getRowsData to retrieve the information, but I would like to modify the values stored within a JS object and then write that modified value back into the cell. I would like to use the normalized header variable that was created with getRowsData to write back into the cell. So if I retrive the info using
var thirdEmployee = employeeObjects[2];
var stringToDisplay = "The third column is: " + thirdEmployee.firstName + " " + thirdEmployee.lastName;
stringToDisplay += " (id #" + thirdEmployee.employeeId + ") working in the ";
stringToDisplay += thirdEmployee.department + " department and with phone number ";
stringToDisplay += thirdEmployee.phoneNumber;
ss.msgBox(stringToDisplay);
Then, for example, I would assign a new value to the Javascript object thirdEmployee.phoneNumber; and then have it written into the proper location in the range (i.e., active row, column # based on header).
thirdEmployee.phoneNumber = "123-555-5555";
thirdEmployee.phoneNumber.setNewValue();
or
setNewValue.thirdEmployee.phoneNumber;
Basically, it would be a modified version of setRowsData but allow for modification of one object and then telling that object to be written into the spreadsheet based on the active row & column based on the header.
Anyone use or know how to do this?
The setRowsData() helper function from the Writing Data from JavaScript Objects to a Spreadsheet tutorial already supports the ability to write a single object. To use it, though, you need to provide both of the optional parameters optHeadersRange and optFirstDataRowIndex.
If we assume that your headers are in row 1, here's how you could update thirdEmployee:
var headersRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var thirdEmployee = employeeObjects[2];
...
thirdEmployee.phoneNumber = "123-555-5555";
setRowsData(sheet, [thirdEmployee], headersRange, 3 );

Categories