Error running SQL statement generated in code - mysql

String query = "INSERT INTO `new_db2`(`name`, `price`, `add_date`, `image`) " + "VALUES ('"+name+"','"+p_price+"','"+date+"','"image"')";
i have ';' error expected in this Sql query please help me to solve this

I don't know the language you are using (I suppose Java) but may be you should write the statement like this:
String query = "INSERT INTO `new_db2`(`name`, `price`, `add_date`, `image`) " + "VALUES ('"+name+"','"+p_price+"','"+date+"','"+image+"')";
(lack of + before and after image)

Related

Node.js mysql Syntax Error in Merge Statement?

I have an sql query that is Constructed as follows:
tmpQUERY = "INSERT INTO vertix_users (user_name, user_email, user_pass) " +
"VALUES (" + mysql.escape(userName) +
", " + mysql.escape(userEmail) +
", " + mysql.escape(userPass) + ")";
tmpQUERY = "MERGE vertix_users WITH (HOLDLOCK) AS oldData " +
"USING (VALUES (#user_name, #user_email)) AS newData (" + mysql.escape(userName) + ", " + mysql.escape(userEmail) + ") " +
"ON newData.user_name = oldData.user_name AND newData.user_email = oldData.user_email " +
"WHEN NOT MATCHED BY TARGET THEN " + tmpQUERY;
When I execute the code, I get the following log:
MERGE vertix_users WITH (HOLDLOCK) AS oldData USING (VALUES (#user_name, #user_email)) AS newData ('asfasfsaff vvv', 'asfasfasfasf') ON newData.user_name = oldData.user_name AND newData.user_email = oldData.user_email WHEN NOT MATCHED BY TARGET THEN INSERT INTO vertix_users (user_name, user_email, user_pass) VALUES ('asfasfsaff vvv', 'asfasfasfasf', 'saqqq')
And a sql syntax error that reads:
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 'MERGE vertix_users WITH (HOLDLOCK) AS oldData USING (VALUES (#user_name, #user_e' at line 1]
A simple insert statement without the merge works fine, but as soon as I add the second portion of that code, it creates that error.
MERGE is not supported by MySQL, The equivalent for that is
INSERT ... ON DUPLICATE KEY UPDATE

Inserting an SQL query string into an SQL table

I want to insert an SQL query string into my database, but I always get an error because of the single quotes ''. I can't just double them '''', because then I can't execute the SQL query which is stored in the SQL database. Here is an example:
"INSERT INTO selections(selection_name, selection_sql, selection_besitzer, selection_sichtbarkeit, selection_standardSelektion)"
+ "VALUES ('"
+ "TestName"+"', '"
+ "Select * From customer where customer_adressnummer like '%1%';"+"', '"
+ "Select all from customer where X"+"', '"
+ "private"+"', '"
+ "0"+"')");
My question is: How can I insert this query into my SQL database without changing the String?
After I insert it I want to read it with my program and then execute the query based on the String in my database.
Here's the error message:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'Select * From customer where customer_adressnummer like '
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3374)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2543)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1737)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2022)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1940)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1925)
at toolhouseserver.ExecutionThread.run(ExecutionThread.java:114)
at java.lang.Thread.run(Thread.java:745)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Not surprisingly, the probability of encountering SQL injection issues is rather high when trying to use dynamic SQL to insert SQL strings into an SQL database. Save yourself the grief and just use a parameterized query, like this:
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO selections (selection_name, selection_sql, selection_besitzer, selection_sichtbarkeit, selection_standardSelektion) " +
"VALUES (?,?,?,?,?)");
ps.setString(1, "TestName");
ps.setString(2, "Select * From customer where customer_adressnummer like '%1%';");
ps.setString(3, "Select all from customer where X");
ps.setString(4, "private");
ps.setString(5, "0");
ps.executeUpdate();

how to handle very long SQL INSERT statement in mysql

I am using the following (python) code to generate a (MySQL) SQL INSERT statement (there are more columns, I left them out for simplicity):
mylist = [('1', '2', '3'),
('4', '5', '6'),
.
.
.
('7', '8', '9')]
sql_statement = "insert into mytable (col1, col2, col3) values "
for i in mylist:
if sql_statement == "insert into mytable (col1, col2, col3) values ":
# append this for the 1st element
sql_statement += "(" + i[0] + ", " + i[1] + ", " + i[2] + ")"
else:
# append this for everything else
sql_statement += ", (" + i[0] + ", " + i[1] + ", " + i[2] + ")"
which results in a string like the following:
sql_statement = "insert into mytable (col1, col2, col3) values (1, 2, 3), (4, 5, 6), ... (7, 8, 9)"
I then use sql_statement to execute the sql statement.
the issue with this approach is that the sql_statement string is getting to long and the insert does not consider all data.
any suggestions how to handle this?
UPDATE: prepared statement is the way to go. with that the (python) code looks like this:
sql_statement = "insert into mytable (col1, col2, col3) values (%s, %s, %s)"
for i in mylist:
cursor.execute(sql_statement, i)
Does the python library you are using supported prepared parameterized queries? I've found the performance difference between multi-value inserts such as this and repeated executions of prepared statements (in .Net at least) to be minimal in all but extreme cases. (In those cases, a mix of the two is optimal.)
Alternatively, just keep track of your query length, execute before it gets too big, and reinitialize the string & continue until all rows are handled.
Create a transaction and do insert one by one. and finally commit it. So only in one call all insert operation commit.

Function NOW() on Qt

I'm trying to implement this query with Qt:
mysqlpp::Query query = acdb.query();
query << "INSERT INTO jobs (jobType, creationDate, reelType)
VALUES('ARCHIVE', NOW(), '" + reelType + "')";
where NOW() returns the current date and time.
This my code on Qt:
QSqlQuery query;
query.prepare("INSERT INTO jobs (jobType, creationDate, reelType) VALUES ('ARCHIVE',
'NOW()', '" + reelType + "')");
here NOW returns 0000-00-00 00:00:00
Is there a similar function?
You are trying to insert the string value 'NOW()' into the datetime field, hence resulting in an invalid value:
"INSERT INTO jobs (jobType, creationDate, reelType) VALUES ('ARCHIVE',
'NOW()', '" + reelType + "')");
Replace it with:
"INSERT INTO jobs (jobType, creationDate, reelType) VALUES ('ARCHIVE',
NOW(), '" + reelType + "')");
Btw. NOW() is a pure SQL function. It doesn't matter which platform or framework you use to send the query, it is entirely evaluated by the SQL server.

SQL table accepting same names again and again database name checking

I am trying to insert the guestpass type name in table guestpasstypes and at a time it will check the database whether the database has already that name or not by using this statement:
#"INSERT INTO guestpasstypes(guestPasstype_Name)values('" + tbPassType.Text + "') where not exists (select 'guestPasstype_Name' from guestpasstypes where guestPasstype_Name = '" + tbPassType.Text + "')"
but it accepts the duplicate name too, and it does not work. Would anyone please help on this?
For SQL Server it would look like this.
insert into guestpasstypes (guestPasstype_Name)
select 'name1'
where not exists (select *
from guestpasstypes
where guestPasstype_Name = 'name1')
I think it should work for MySQL as well.
If you are on SQL Server 2008 you can use MERGE.
merge guestpasstypes as G
using (select 'name2') as S(Name)
on G.guestPasstype_Name = S.Name
when not matched then
insert (guestPasstype_Name) values (Name);
UPDATE
I think the first option could be applied to your problem like this:
#"INSERT INTO guestpasstypes(guestPasstype_Name) select '" + tbPassType.Text
+ "' where not exists (select * from guestpasstypes where guestPasstype_Name = '"
+ tbPassType.Text + "')"
If you want it to throw an error you can either :
Put a unique index on the column (the easiest and preferred way)
or
Write a stored procedure which returns an error flag. Within the procedure, you first check for a matching value and if one is found, set the error flag and return. Otherwise do the insert as normal.
Try either INSERT IGNORE or INSERT ON DUPLICATE KEY:
INSERT IGNORE INTO `guestpasstypes`(`guestPasstype_Name`) values('" + tbPassType.Text + "');
OR
INSERT INTO `guestpasstypes`(`guestPasstype_Name`)values('" + tbPassType.Text + "') ON DUPLICATE KEY UPDATE `guestPasstype_Name` = `guestPasstype_Name`;