Reputation: 1494
Tried This Code But it gives "ER_PARSE_ERROR"
Err Description: "sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Insert values ('Bitcoin')' at line 1"
var query = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10)) Insert values ('" + projectName + "')";
I want to Insert a new Project in the Projects Table, create the table if it does not exists and insert the record, I can write multiple queries for this work and check response if success then proceed with the next query but I am looking for a query which does all the work concatenating multiple queries in itself.
Note: I am using mysql module in Nodejs
The process should work synchronously one after the other, when a user sends a post request to the route '/add_project' with data in body "project_name":"project1" then the server inserts the record in the mysql table projects but it generates err "No such Table " if that was the first record. I want it to work synchronously first by creating the table if not exists and then inserting the record.
Edit: Added screenshot for @Nick suggestion
Upvotes: 1
Views: 4227
Reputation: 147206
You could use CREATE TABLE ... SELECT
syntax:
var query = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10)) SELECT '" + projectName + "' AS project_name";
Upvotes: 1
Reputation: 1494
Working Code But I need to get less complicated code without much error handling:
app.post('/add_project_to_database',function(req,res){
var projectName = req.body.project_name;
//CHECK IF PROJECT EXISTS
var query = "Select project_name from projects where project_name = '" + projectName + "'";
return res.send('Project Already Exists!');
//INSERTING PROJECT
// var query = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10)) Insert values ('" + projectName + "')";
var query = "Insert into projects(project_name) values ('" + projectName + "')";
con.query(query, function(err, result){
if(err){
var query_create = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10))";
con.query(query_create,function(error,res_create){
if(error){
console.log(error);
res.send(error);
}
else{
console.log("TABlE CREATED");
con.query(query,function(error_insert,response){
if(error_insert){
console.log(error_insert);
res.send(error_insert);
}
else{
console.log("RECORD INSERTED SUCCESSFULLY !");
}
});
}
});
}else{
res.send("Successfully Inserted Project");
}
});
});
Upvotes: 1