I am using HTML5 web storage for storing data locally. I want to store the JSON data into database. For that i am converting the JSON as string using JSON.stringify(obj).
But, I could not able to storing the data. can any body suggest the best approach?
var customerStr = JSON.stringify($scope.indexData);
var db = openDatabase('customerDB', '1.0', 'customer DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS CUSTOMER (id unique, userid, customerdata VARCHAR)');
tx.executeSql('INSERT INTO CUSTOMER (id, userid, customerdata) VALUES (1, 2, customerStr)');
console.log('<p>Log message created and row inserted.</p>');
});
I think there is some confusion as posted code and title differs.
Code you have posted is creating a table if not exists and inserting a record.
however create table line is not correct as datatype of userid is missing.
try to run this sql in query analyser to find out syntax error
'CREATE TABLE IF NOT EXISTS CUSTOMER (id unique, userid, customerdata VARCHAR)'
Take a look here for how to use HTML5 WEb storage
you can use localstorage as below.
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Related
I am working on a react app with a Node/Express JS back end.
I am trying to insert a value, based on the input of the user, into MySQL database. Here is my Node post request:
// To create a new user account
app.post('/createUser', function(req, res) {
console.log('in createUser');
const {firstName, lastName, username, passcode, email} = req.query;
const CreateUser = `CALL CreateUser('${firstName}', '${lastName}',
'${username}', '${passcode}', '${email}')`;
mysqlConnection.query(CreateUser, (error, result) => {
if(error) {
res.status(500)
res.send("Could not create user account.")
} else {
console.log('create user cart');
console.log(`${req.query.username}`);
const CreateUserCart = `CALL CreateUserCart('${req.query.username}')`;
mysqlConnection.query(CreateUserCart, (error1, result1) => {
if(error1) {
res.status(500)
res.send("Could not create user account.")
} else {
res.status(201)
res.send("Account successfully created!")
}
})
}
})
});
The first stored procedure, CreateUser, is working fine. What I want to do is take the value in req.query of username and pass it to the stored procedure called CreateUserCart. Here is that stored procedure:
CREATE DEFINER=`lsharon`#`%` PROCEDURE `CreateUserCart`(IN
username VARCHAR(45)
)
BEGIN
INSERT INTO SHOPPING_CART(CustomerID)
SELECT CustomerID
FROM CUSTOMER
WHERE Username = username;
END
My desire is to insert the CustomerID that belongs to the user I just created into the shopping cart table. However, currently it is inserting every CustomerID into that table, even if it already exists there. I only want to insert the ID for the single user who just created an account.
Any suggestions would be appreciated!!
The query in your sp says
WHERE Username = username;
Your column names are case insensitive. So Username = username matches every row in your CUSTOMER. It's a version of WHERE 1 = 1 -- always true.
Try changing the name of your parameter, something like this:
CREATE PROCEDURE `CreateUserCart` (IN newUsername VARCHAR(45) )
BEGIN
INSERT INTO SHOPPING_CART(CustomerID)
SELECT CustomerID
FROM CUSTOMER
WHERE Username = newUsername;
END
MySQL stored programs are tons of fun to troubleshoot, eh? Lots of people avoid them for that reason. On the other hand, many large enterprises use lots of stored programs to interact with their data. But those enterprises usually pay the rather large licensing fees for Oracle or SQL Server. Those databases have better stored programming languages and tools. So, if you work at one of those places, you'll appreciate having a little bit of exposure to stored programs.
Pro tip there's a much more robust way to handle this workflow. Get your first stored procedure to end with something like
SELECT LAST_INSERT_ID() CustomerID;
This will make the procedure return a resultset, which you can handle just as if it were a SELECT query. LAST_INSERT_ID() gets the autoincrement value from the most recent INSERT.
Then read that customer id from your resultset, and pass it as a parameter to CreateUserCart rather than the customer's name.
I have the following code that I used for inserting into MySQL (MariaDB)....
import mysql from "mysql";
const INSERT_QUERY = "INSERT INTO CALL_DATE SET ? ON DUPLICATE KEY UPDATE MADE_DATE = VALUES(MADE_DATE)";
insertCallDate(callId, server, date){
const callDate = {
...
};
return connection.query(
INSERT_QUERY,
callDate
);
}
When I move to oracleDB I would like to do something like that again but the closest I can find is something like...
const INSERT_QUERY = "INSERT INTO CALL_DATE SET (ID, ...) values (:1, ...)";
Is there something similar to MySQL so I can pass a prestructured JSON object to Oracle? Specifically using the Node JS oracledb library?
There's a short section on JSON in the node-oracledb documentation. To quote an example:
const data = { "userId": 1, "userName": "Chris", "location": "Australia" };
const s = JSON.stringify(data); // change JavaScript value to a JSON string
const result = await connection.execute(
`INSERT INTO j_purchaseorder (po_document) VALUES (:bv)`,
[s] // bind the JSON string
);
There are also two runnable examples: selectjson.js and selectjsonblob.js.
Most of the JSON technology in Oracle is not specific to node-oracledb, so the Oracle manual Database JSON Developer’s Guide is a good resource.
You may be interested in SODA, which is also documented for node-oracledb and has an example, soda1.js. It lets you store 'documents' in the DB. These documents can be anything, but by default JSON documents are used.
I have a table looks like this:
id url title
1 http://afef.com/abc/def/gje/qkd hello
2 http://afe.com/?a=3&b=2&fse=3 hello
3 http://stackoverflow.com/fefw/sefac/fsg hello-world
from here id is primary key and auto_increment, and url is unique, but title can be duplicated.
From this point of view, when I add new URL to this table, like :
INSERT IGNORE INTO table (url, title)
VALUES ('http://abcd.com/affefef/sfsaa/?a=3', 'this is title')
Then, if it is new URL to insert, it doesn't matter. But if it is duplicated URL, it will be ignored and I can't know what the duplicated URL's id is.
The id must not be changed.
Is there any solutions to know id when I INSERT duplicated URL with one query ?
Conditionally checking would help in getting duplicate ID
Check this code:
mysql.query("SELECT id FROM table WHERE url = 'http://abcd.com/affefef/sfsaa/?a=3", function(error, result, field) {
if(error) {
exist(error); //No error
} else if (result) {
if (result.length > 0){
console.log("Id exist:" + result['id']);
}else{
// write your insert statement here
}
}
});
In one query only, I think it's not possible. But you can use the Mysql function "last_insert_id" to retrieve the id which has been inserted. Checking it, you would be able to see if it's a new one or not.
See http://www.mysqltutorial.org/mysql-last_insert_id.aspx
You can also have a look at "insert on duplicate". With this syntax it will update the field if it exists or inserts a new one if the key isn't found.
https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
SQL Server 2008 Ent
ASP.NET MVC 2.0
Linq-to-SQL
I am building a gaming site, that tracks when a particular player (toon) had downed a particular monster (boss). Table looks something like:
int ToonId
int BossId
datetime LastKillTime
I use a 3d party service that gives me back latest information (toon,boss,time).
Now I want to update my database with that new information.
Brute force approach is to do line-by-line upsert. But It looks ugly (code-wise), and probably slow too.
I think better solution would be to insert new data (using temp table?) and then run MERGE statement.
Is it good idea? I know temp tables are "better-to-avoid". Should I create a permanent "temp" table just for this operation?
Or should I just read entire current set (100 rows at most), do merge and put it back from within application?
Any pointers/suggestions are always appreciated.
An ORM is the wrong tool for performing batch operations, and Linq-to-SQL is no exception. In this case I think you have picked the right solution: Store all entries in a temporary table quickly, then do the UPSERT using merge.
The fastest way to store the data to the temporary table is to use SqlBulkCopy to store all data to a table of your choice.
If you're using Linq-to-SQL, upserts aren't that ugly..
foreach (var line in linesFromService) {
var kill = db.Kills.FirstOrDefault(t=>t.ToonId==line.ToonId && t.BossId==line.BossId);
if (kill == null) {
kill = new Kills() { ToonId = line.ToonId, BossId = line.BossId };
db.Kills.InsertOnSubmit(kill);
}
kill.LastKillTime = line.LastKillTime;
}
db.SubmitChanges();
Not a work of art, but nicer than in SQL. Also, with only 100 rows, I wouldn't be too concerned about performance.
Looks like a straight-forward insert.
private ToonModel _db = new ToonModel();
Toon t = new Toon();
t.ToonId = 1;
t.BossId = 2;
t.LastKillTime = DateTime.Now();
_db.Toons.InsertOnSubmit(t);
_db.SubmitChanges();
To update without querying the records first, you can do the following. It will still hit the db once to check if record exists but will not pull the record:
var blob = new Blob { Id = "some id", Value = "some value" }; // Id is primary key (PK)
if (dbContext.Blobs.Contains(blob)) // if blob exists by PK then update
{
// This will update all columns that are not set in 'original' object. For
// this to work, Blob has to have UpdateCheck=Never for all properties except
// for primary keys. This will update the record without querying it first.
dbContext.Blobs.Attach(blob, original: new Blob { Id = blob.Id });
}
else // insert
{
dbContext.Blobs.InsertOnSubmit(blob);
}
dbContext.Blobs.SubmitChanges();
See here for an extension method for this.
My workplace doesn't use identity columns or GUIDs for primary keys. Instead, we retrieve "next IDs" from a table as needed, and increment the value for each insert.
Unfortunatly for me, LINQ-TO-SQL appears to be optimized around using identity columns. So I need to query and update the "NextId" table whenever I perform an insert. For simplicity, I do this during the creation of the new object:
var db = new DataContext( "...connection string..." );
var car = Car
{
Id = GetNextId<Car>( db ),
TopSpeed = 88.0
};
db.InsertOnSubmit( car );
db.SubmitChanges();
The GetNextId method is something like this:
public int GetNextId<T>( DataContext db )
{
using ( var transaction = new TransactionScope ( TransactionScopeOption.RequiresNew ) )
{
var nextId = (from n in db.GetTable<NextId> ()
where n.TableName == typeof(T).Name
select n).Single ();
nextId.Value += 1;
db.SubmitChanges ();
transaction.Complete ();
return nextId.Value - 1;
}
}
Since all operations between creation of the data context and the call to SubmitChanges are part of one transaction, do I need to create a separate data context for retrieving next IDs? Each time I need an ID, I need to query and update a table inside a transaction to prevent multiple apps from grabbing the same value. The call to SubmitChanges() in the GetNextId() method would submit all previous operations, which I don't want to do.
Is a separate data context the only way, or is there something better I could try?