What is syntactically wrong with this ON DUPLICATE KEY UPDATE query? - mysql

Update: This issue was resolved in the comments and is awaiting an answer
When executing the following query in PyMySQL, I receive the error ‘1064, u"You have an error in your SQL syntax;’ (full error message below)
INSERT INTO `table_name` (`id`, `colName1`, `colName2`, `colName3`)
VALUES (820, 'string', 5, 'N')
ON DUPLICATE KEY UPDATE
`colName1`=VALUES(`colName1`),
`colName2`=VALUES(`colName2`),
`colName3`=VALUES(`colName3`)
-- Tried with and without ` surrounding column names after ON DUPLICATE KEY UPDATE
Syntax in Python:
sql = "INSERT INTO `table_name` (`id`, `colName1`, `colName2`, `colName3`) VALUES (820, 'string', 5, 'N') ON DUPLICATE KEY UPDATE `colName1`=VALUES(`colName1`),`colName2`=VALUES(`colName2`),`colName3`=VALUES(`colName3`)"
I received this error both when trying to update many rows (as suggested elsewhere, using the format of the accepted answer), and for one row at a time.
As noted in the comments, the stripped down example didn't produce an error (although it was not executed with Python). The following is the actual query. Let me know if other information is needed.
Query string executed in Python:
INSERT INTO `Listings` (`id`, `row_last_updated`, `maxBidCountPreRsvMet`, `maxBidPreRsvMet`, `minBidCountPostRsvMet`, `occupancy_status`, `waitingForHnb`, `ownItNow_price`, `high_bid`, `prop_id`, `hot_property`, `status`, `end_date`, `reserve_met`, `hours`, `backupBidSet`, `listing_type`, `low_bid`, `winning_bid`, `bids`, `days`, `high_bid_updated`, `minutes`, `lowBidIsOpt1`) VALUES (820, '2018-01-28 19:16:02', '5', '234000', None, 'N', None, 0, 234000, u'9007092665103', 'N', 'New', '2018-1-31-22-0', 'N', 7, 0, 'AUCN', 0, 0, 5, 3, '2018-01-28 14:16:02.001906', 44, 0) ON DUPLICATE KEY UPDATE `row_last_updated`=VALUES(`row_last_updated`),`maxBidCountPreRsvMet`=VALUES(`maxBidCountPreRsvMet`),`maxBidPreRsvMet`=VALUES(`maxBidPreRsvMet`),`minBidCountPostRsvMet`=VALUES(`minBidCountPostRsvMet`),`occupancy_status`=VALUES(`occupancy_status`),`waitingForHnb`=VALUES(`waitingForHnb`),`ownItNow_price`=VALUES(`ownItNow_price`),`high_bid`=VALUES(`high_bid`),`prop_id`=VALUES(`prop_id`),`hot_property`=VALUES(`hot_property`),`status`=VALUES(`status`),`end_date`=VALUES(`end_date`),`reserve_met`=VALUES(`reserve_met`),`hours`=VALUES(`hours`),`backupBidSet`=VALUES(`backupBidSet`),`listing_type`=VALUES(`listing_type`),`low_bid`=VALUES(`low_bid`),`winning_bid`=VALUES(`winning_bid`),`bids`=VALUES(`bids`),`days`=VALUES(`days`),`high_bid_updated`=VALUES(`high_bid_updated`),`minutes`=VALUES(`minutes`),`lowBidIsOpt1`=VALUES(`lowBidIsOpt1`)
The full error message:
(1064, u"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 ''9007092665103', 'N', 'New', '2018-1-31-22-0', 'N', 7, 0, 'AUCN', 0, 0, 5, 3, '2' at line 1")
Side notes: Python None values are converted to MySQL null values. The same error occurred when changing None values to strings.

Related

Why is this my sql statement wrong in the navicat? [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
INSERT INTO ry_useraccount
(
'Id',
'UserId',
'FreeAmount',
'PayFrozenAmount',
'WithdrawFrozenAmount',
'CurrentAsset',
'CreateTime',
'UpdateTime'
) VALUES
(
'1',
'52501',
'600',
'0',
'0',
'0',
NOW(),
NOW()
);
If just look at the sql,it is correct,but when I run it,the navicat said
“[SQL]INSERT INTO ry_useraccount('Id', 'UserId', 'FreeAmount',
'PayFrozenAmount', 'WithdrawFrozenAmount', 'CurrentAsset',
'CreateTime', 'UpdateTime') VALUES('1', '52501', '600', '0', '0', '0',
NOW(), NOW()); [Err] 1064 - 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 ''Id', 'UserId', 'FreeAmount',
'PayFrozenAmount', 'WithdrawFrozenAmount', 'Curren' at line 1”
. I cannot find the reason.I guess that maybe some white space cause the result,but after I delete all the white spaces,it still didn't work.
The single quote are for literal string not for column name (you can use backticks if you need column name with space or with reserved words )
INSERT INTO ry_useraccount(Id, UserId, FreeAmount, PayFrozenAmount, WithdrawFrozenAmount, CurrentAsset, CreateTime, UpdateTime)
VALUES(1, 52501, 600, 0, 0, 0, NOW(), NOW());

Subquery with MySql using INSERT

I'm trying to update the database, using a script where the ID of a user isn't readily known, so I'm using a subquery to have mysql find the user id (for the posteruserid value). This is the SQL query i'm using:
INSERT INTO `thread` (`title`, `forumid`, `open`, `replycount`,
`postercount`, `postusername`, `postuserid`, `lastposter`,
`dateline`, `visible`, `keywords`)
SELECT 'IN', 2, 1, 0, 1, 'lemons', `userid` FROM `user`
WHERE `username` = 'lemons', 'lemons', 1375768440, 1, 'IN';
I'm getting a syntax error from the above SQL, and I can't figure out what I'm doing wrong.
EDIT because of the mismatched column name, I tried using an alias, which still doesn't work
INSERT INTO `thread` (`title`, `forumid`, `open`, `replycount`,
`postercount`, `postusername`, `postuserid`, `lastposter`,
`dateline`, `visible`, `keywords`)
SELECT 'IN', 2, 1, 0, 1, 'lemons',
`userid` AS `postuserid` FROM `user` WHERE `username` = 'lemons',
'lemons', 1375768440, 1, 'IN';
column mismatch in insert and select query..column should be same where you are going to insert and from where you are fetching data.
You specify to insert values of 11 columns, but in your SELECT statement, you are providing only 7 values. Please provide the value for lastposter,dateline,visible, and keywords.

Error on SQL insert statement

I exported a recordset from one database into a csv file, and when I try to import it into another using mysql workbench I keep this this error message:
Executing SQL script in server
ERROR: Error 1064: 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 ' 'Lord it Over', 'Ben', '1993-03-01', 'TRC', NULL, 1983, '1999-09-01', 'NULL', '' at line 1
INSERT INTO `TRC`.`horse`
(`horse_id`, `registered_name`, `stable_name`, `arrival_date`, `last_known_location`, `is_ex_racer`, `birth_year`, `death_date`, `horse_comments`, `sex`, `referral_date`, `horse_height`, `arrival_weight`, `passport_no`, `microchip_no`, `is_on_waiting_list`) VALUES
(, 'Lord it Over', 'Ben', '1993-03-01', 'TRC', NULL, 1983, '1999-09-01', 'NULL', 'NULL', 'NULL', NULL, NULL, 'NULL', 'NULL', 0)
SQL script execution finished: statements: 29 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
Any help would be appreciated as their appears to be no errors as far as I can see.
It's becaose of
VALUES starts with a comma.
You have missed horse_id. If it's Identity Column Then Remove horse_Id
Try like this (If horse_Id is identity)
INSERT INTO `TRC`.`horse`
(`registered_name`, `stable_name`, `arrival_date`, `last_known_location`, `is_ex_racer`, `birth_year`, `death_date`, `horse_comments`, `sex`, `referral_date`, `horse_height`, `arrival_weight`, `passport_no`, `microchip_no`, `is_on_waiting_list`) VALUES
('Lord it Over', 'Ben', '1993-03-01', 'TRC', NULL, 1983, '1999-09-01', 'NULL', 'NULL', 'NULL', NULL, NULL, 'NULL', 'NULL', 0)
Or (If Horse_id simple int then try this)
INSERT INTO `TRC`.`horse`
(`horse_id`, `registered_name`, `stable_name`, `arrival_date`, `last_known_location`, `is_ex_racer`, `birth_year`, `death_date`, `horse_comments`, `sex`, `referral_date`, `horse_height`, `arrival_weight`, `passport_no`, `microchip_no`, `is_on_waiting_list`) VALUES
('1','Lord it Over', 'Ben', '1993-03-01', 'TRC', NULL, 1983, '1999-09-01', 'NULL', 'NULL', 'NULL', NULL, NULL, 'NULL', 'NULL', 0)
^^^^ -- Here Horse_Id missing
it seems that you missing your "horse_id" value.
If that field was intended to be the Identity field, then you shouldn't mention that field on Insert Statement right?
If you want MySQL to generate an auto_increment ID for the horse_id field, you should either leave it out of the INSERT statement entirely, or specify NULL for the value in the VALUES list. You can't just leave that value empty in the list.
Your VALUES starts with a comma for some reason

Executing Sql script file in Groovy/Gradle

def db = [
moduleGroup: 'mysql',
moduleName: 'mysql-connector-java',
moduleVersion: '5.1.18',
driver: "com.mysql.jdbc.Driver",
url: 'jdbc:mysql://localhost:3306/bham',
user: mySqlUser,
password: mySqlPassword
]
configurations {
sql
}
task connect << {
// This is needed to get mySql driver onto the Groovy/Gradle classpath
configurations.sql.each { file ->
println "Adding URL: $file"
gradle.class.classLoader.addURL(file.toURI().toURL())
}
def sql = groovy.sql.Sql.newInstance(db.url, db.user, db.password, db.driver)
sql.execute("actStatusCodeLkp.sql")
String sqlFilePath = "src/main/resources/sqlscripts/actStatusCodeLkp.sql"
String sqlString = new File(sqlFilePath).text
sql.execute(sqlString)
sql.close()
}
actStatusCodeLkp.sql
insert into act_status_code (id, code, display_name, code_system_name, code_system) values (1, 'active', 'active', 'ActStatus', '2.16.840.1.113883.5.14');
insert into act_status_code (id, code, display_name, code_system_name, code_system) values (2, 'cancelled', 'cancelled', 'ActStatus', '2.16.840.1.113883.5.14');
insert into act_status_code (id, code, display_name, code_system_name, code_system) values (3, 'aborted', 'aborted', 'ActStatus', '2.16.840.1.113883.5.14');
insert into act_status_code (id, code, display_name, code_system_name, code_system) values (4, 'completed', 'completed', 'ActStatus', '2.16.840.1.113883.5.14');
It seems that sql.execute command does not tokenize the file into 4 different insert statements and throws.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 into act_status_code (id, code, display_name, code_system_name, code_syst' at line 2
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
It works if I just keep one insert statement in the file. What is the clean work around here, did not really find anything regarding this online.
Also, when using maven, I am able to run the same sql file using sql-maven-plugin.
Something like this helped me. Notice getting allowMultiQueries: 'true' in the properties
def props = [user: grailsApplication.config.dataSource.username, password: grailsApplication.config.dataSource.password, allowMultiQueries: 'true'] as Properties
def url = grailsApplication.config.dataSource.url
def driver = grailsApplication.config.dataSource.driverClassName
def sql = Sql.newInstance(url, props, driver)
You could also change your sql to make the statement one query by:
insert into act_status_code (id, code, display_name, code_system_name, code_system) values
(1, 'active', 'active', 'ActStatus', '2.16.840.1.113883.5.14'),
(2, 'cancelled', 'cancelled', 'ActStatus', '2.16.840.1.113883.5.14'),
(3, 'aborted', 'aborted', 'ActStatus', '2.16.840.1.113883.5.14'),
(4, 'completed', 'completed', 'ActStatus', '2.16.840.1.113883.5.14');

Drupal 6 db insert: Strings are getting escaped

Getting driven crazy by this one...
I'm trying to insert a number of rows into a D6 database with a single db_query call. I've collected the rows as a set of strings, and have then collected them into one big string, something like so:
$theData = "(1, 2, 'a'), (3, 4, 'b'), (5, 6, 'c')";
db_query("insert into {table} (int1, int2, str) values %s", $theData);
($theData isn't typed like that in my code; it's the result of the code I've written -- a big string containing sets of values wrapped up in parens.)
When this runs, I get an error like:
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 into
table (int1, int2, str) values (1,2,\'a\' at line 1 query: insert into
table (int1, int2, str) values (1,2,\'a\'),(3,4,\'n\'),(5,6,\'c\')...
So, db_query or somebody else is escaping the strings before passing the values of to mysql. How do I keep this from happening? I could do individual queries for each set of data, but that's wrong/expensive for all the obvious reasons. Thanks!
$theDatas = array("(1, 2, 'a')", "(3, 4, 'b')", "(5, 6, 'c')");
foreach($theDatas as $data) {
db_query("insert into {table} (int1, int2, str) values %s", $data);
}
But it's not recommend to do that, instead of this you should:
$theDatas = array(array(1, 2, 'a'), array(3, 4, 'b'), array(5, 6, 'c'));
foreach($theDatas as $data) {
db_query("insert into {table} (int1, int2, str) values (%d, %d, '%s')", $data[0], $data[1], $data[2]);
}
Or you can serialize($theData) and put it "text" format field as one value, then use unserialize() for restoring array - this way is recommend if you want only store data (no searching, indexing etc).