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
You could use CREATE TABLE ... SELECT syntax:
var query = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10)) SELECT '" + projectName + "' AS project_name";
Demo on rextester
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");
}
});
});
Related
I am trying to follow the following blog and use an UPDATE, IF, INSERT INTO statement seeing that it will no go over my data twice.
Please note it is for php.
The statement that I have is as follows
$query = "UPDATE
" . $this->table_name2 . "
SET
batch = :batch,
created = :created
WHERE
id = :id
IF row_count() = 0
INSERT INTO " . $this->table_name2 . "
SET
id=:id,
batch=:batch,
created=:created";
But my return value always comes back as false, and I do not know where the problem is.
If I try the first half of the statement it updates the information:
$query = "UPDATE
" . $this->table_name2 . "
SET
batch = :batch,
created = :created
WHERE
id = :id
And if I try the second half of the statement it INSERTS the information:
INSERT INTO " . $this->table_name2 . "
SET
id=:id,
batch=:batch,
created=:created";
I do not find any help after allot of searching so far, and I feel that somehow my IF statement may not be correct, but I do not even get info on the IF row_count() = 0 in the docs.
The IF statement is available in stored procedures only.
If id is the primary key (or unique) this should work for you:
INSERT INTO " . $this->table_name2 . "
SET
id = :id,
batch = :batch,
created = :created
ON DUPLICATE KEY UPDATE
batch = :batch,
created = :created
This will execute the INSERT statement only, of the ID does not exits yet. If it already exists, it will execute the UPDATE part.
Trying to insert data into mysql with 'INSERT INTO users SET ?', I get 500 error in front end. data is reaching the server but unable to insert into database. Tried even 'INSERT INTO users VALUES ?' but still fails. i'm able to retrieve the data from the database('SELECT * FROM users') but not inserting it.
router.post('/userstuff', function(req, res, next) {
var eachuser = {
name: req.body.name,
age: req.body.age
};
connection.query('INSERT INTO users SET ?',eachuser, function(err, rows){
if(err) console.log('Error selecting: %s ', err);
console.log(rows)
});
});
edit: added the schema:
use 02sqldb;
CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30),
age int(2)
);
And what if you try to first do a dummy query. I don't know for sure you can simply put "?" to insert a value without giving a column like
'INSERT INTO table_name (column1,column2,column3,...)
VALUES ('?','?','?',...)'
If it still isn't working you know it's something else.
With a conditional Insert, I want to know if a row was inserted or if overlap was found.
I have a query that inserts a request into the database if it doesn't overlap with any existing entry. The query works, but how do I know if there's been an collision? The query just executes successfully. Here is my query:
INSERT INTO requests(id, start_time, end_time)
SELECT NULL, 1463631640671,1463636731000,
FROM Dual
WHERE NOT EXISTS (
SELECT * FROM requests
WHERE
start_time < 1463638531000 AND
end_time > 1463636731000
)
For your information. I'm doing this inside Node.js with the mysql package.
and the code looks like this, and it returns 'SUCCESS' every time.
var queryString = "INSERT INTO requests(id, start_time, end_time..."
connection.query(queryString, function(error, results, fields) {
if (!error) {
console.log('SUCCESS!');
}
else {
console.log('Insert into requests unsuccessful.');
console.log('ERROR: ' + error);
}
});
you can inspect results.insertId and see if you have something in it.
I am using Spring-Jdbc template(first timer) to create MySql repository. I have tables that use AutoIncrement columns as primary key.
I wonder if there a way to get newly generated Ids (autoInc) with each successful batch create statement?
Any pointers or sample would be a great help.
Thanks
Panks
Use getGeneratedKeys() method from your Statement or PreparedStatement object to identify the new auto generated values. Iterate the returned ResultSet object to get the newly generated key values in the order of batch statements.
This call may throw java.sql.SQLFeatureNotSupportedException if the JDBC driver, that you are using, does not support this method.
Sample code snippet:
String sql_insert =
"insert into my_table ( non_auto_incrmnt_fld_names_,_separated ) " +
" values ( record1 ), ( record2 )"; // append as many as required
...
int rowsAffected = stmtObject.executeUpdate( sql_insert, Statement.RETURN_GENERATED_KEYS );
ResultSet rs = stmtObject.getGeneratedKeys();
//******************************************************
rs.last();
int rows = rs.getRow();
System.out.println( "Generated keys count: " + rows );
int currentRow = 1;
rs.beforeFirst();
//******************************************************/
while( rs.next() ) {
System.out.println( /**/( currentRow++ ) + " = " + /**/rs.getInt( 1 ) );
} // while rs
I'm trying to add a new mysql column in a table, using an insert_id from an insert of another table. This is the sentence that i use...
string sqlInsert = "INSERT INTO test (IdPico, Nombre, TextoBienvenida, FechaCreacion) VALUES (1, 'nombretest', 'aslkñdfa lsñdk asjd asldkf añlsj f', '2011-07-13 10:22:53'); ";
sqlInsert += "SET #IDTESTCREATED := CONCAT('Test', LAST_INSERT_ID(); ";
sqlInsert += "ALTER TABLE Usuarios ADD COLUMN #IDTESTCREATED BIT DEFAULT 0; ";
I using ASP.NET 4.0 and MySql connection, and server responds with 'Fatal error encountered during command execution. '
Could anybody help me?
Well ... I answer myself.
After making a deep search, I have not found how to add a column dynamically by a variable in mysql.
At end I had to make two querys, first to insert the test and get the id, and second to update the users table.
Since the insertion and retrieval of id are in the same query, no problems of persistent connections and concurrent updates.
string sqlInsert = "INSERT INTO Test (<fields>) VALUES (<values>);";
sqlInsert += "SELECT LAST_INSERT_ID() AS IdTestInserted; ";
string idnewtest = <result of insert query>;
string sqlAlter = "ALTER TABLE Users ADD COLUMN Test" + idnewtest + " BIT DEFAULT 0; ";
I regret not having found the answer, but at least I achieved my goal.
Thank you all for your help!