I'm trying to write a SQL INSERT statement (deliberately not using ActiveRecord), to eventually insert a large number of rows in one go.
inserts.push "('#{x}', #{p}, '#{day.strftime("%Y-%m-%d")}', #{student.id}, '#{created_at}', '#{created_at}', '#{session}')"
sql = "INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES #{inserts.join(", ")}"
conn = ActiveRecord::Base.connection
conn.execute sql
But I get an error because the value of x is "\". How do I get around this and successfully insert the backslash character into the MySQL DB?
It feels like it should be simple, and it probably is, but I've got to my wit's end trying to work it out.
Error message:
>> Attendance.parse_attendance_string Student.find(1), "\\", DateTime.new(2012,9,1)
Student Load (0.7ms) SELECT `students`.* FROM `students` WHERE `students`.`id` = 1 LIMIT 1
(0.4ms) INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES ('\', 1, '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')
ActiveRecord::StatementInvalid: Mysql2::Error: 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 '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')' at line 1: INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES ('\', 1, '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `query'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `execute'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `log'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `execute'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/mysql2_adapter.rb:214:in `execute'
from /Users/mike.campbell/projects/cpoms_messy/app/models/attendance.rb:76:in `parse_attendance_string'
from (irb):115
>>
Rather than sanitize the inputs, deal with backslashes, and join the query all on your own, I would recommend checking out ActiveRecord import. It provides a Gem that lets you semantically create bulk inserts using this syntax:
books = []
10.times do |i|
books << Book.new(:name => "book #{i}")
end
Book.import books
Related
Currently I have a database with the following parameters and entry:
Now I want to fill the column status_from in this particular entry with the id 1 with a substring of the action column. Which is basically I want to fill my status_from column with a word that comes after from and before to of the action column. To achieve this I've tried using the following statement:
INSERT INTO crm_logs2(status_from) SELECT status_from WHERE id='1' VALUES (substring_index(substring_index(action, 'from', -1),'to', 1))
But doing this gave me the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'VALUES (substring_index(substring_index(action, 'from', -1), ...' at line 1
You need to use the UPDATE statement
UPDATE crm_logs2
SET status_from = (SUBSTRING_INDEX(SUBSTRING_INDEX(action, "from", -1), "to", 1))
WHERE id = 1
update crm_logs2
set action=(select SUBSTRING_INDEX(SUBSTRING_INDEX(action, ' ', 6), ' ', -1) from
crm_logs2 where id=1)where id=1
Try this and let us know if it works
sql = ("INSERT INTO {0} "
"(id, timestamp, status, priority, client, group, capacity, level, mail_id) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)".format(TABLE_NAME_MAIL))
values = ('NULL', report['timestamp'], 'succeeded', report['priority'], c.strip(), report['group'], 'NULL', 'NULL', ref_mailid)
cursor.execute(sql, values)
#cursor.execute('INSERT INTO %s VALUES (NULL,"%s","%s","%s","%s","%s",NULL,NULL,"%s") ' % (TABLE_NAME_REPORT, report['timestamp'], 'succeeded', report['priority'], c.strip(), report['group'], ref_mailid))
The commented out cursor.execute works, the uncommented throws an error:
_mysql_exceptions.ProgrammingError: (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 'group, capacity, level, mail_id) VALUES ('NULL', '2014-12-05 23:46:56', 'succeed' at line 1")
Column 'id' has AUTO_INCREMENT
Why am I getting this error?
group is a reserved keyword in MySQL. Use backticks to escape the name
INSERT INTO {0} (id, timestamp, status, priority, client, `group`, capacity ...
here--------------------------------^-----^
or even better use a different column name.
And don't use 'NULL' as parameter. Either use NULL without the quotes or remove it completely from the query:
INSERT INTO {0} (timestamp, ...
^----------no ID
When using an auto increment column, you have two options:
Insert a value in there (ie: Override the auto increment)
Do not set the column at all
1:
In case of setting a value, and you want to set "NULL" the column has to allow a NULL. This is rarely the case with an auto increment column since it would defeat its purpose.
So this is allowed:
INSERT INTO tab (id, sometext) VALUES (10,"Hi");
2:
Alternative (most used) is not to name the column at all:
INSERT INTO tab (sometext) VALUES ("Hi");
which would lead to mysql assigning a value to id in your table.
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.
I'm using import to add rows to a table. I have almost 600 to add but working with just the 2 below for now. My file:
INSERT INTO `wp_wlm_userlevel_options` ( `userlevel_id`, `option_name`, `option_value`, `autoload`) VALUES ( '341', registration_date', '2017-11-30 16:14:43#0', 'yes' ),( '341', 'transaction_id', 'WL-6806-1506616728', 'yes' );
There is an auto generated value (ID) before userlevel_id. I've tried including it with same results. Also tried removing "16:14:43#0" same results.
Full response***********************
Error
Static analysis:
2 errors were found during analysis.
Unexpected character. (near ":" at position 153)
Unexpected character. (near ":" at position 156)
SQL query:
INSERT INTO `wp_wlm_userlevel_options` ( `userlevel_id`, `option_name`, `option_value`, `autoload`) VALUES ( '341', registration_date', '2017-11-30 16:14:43#0', 'yes' ), ( '341', 'transaction_id', 'WL-6806-1506616728', 'yes' )
MySQL said: Documentation
#
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 '', '2017-11-30 16:14:43#0', 'yes' ), ( '341',
'transaction_id', 'WL-6806-1506' at line 2)
Any help appreciated!! Thanks
Why does the following query fails on MySql?
NHibernate: INSERT INTO UserSetting (userId, key, value) VALUES (?p0, ?p1, ?p2);
?p0 = ccda78da-689d-4d86-ba72-d65eaf281edf [Type: Guid (0)], ?p1 = 'Hello' [Type: String (5)], ?p2 = 'World' [Type: String (5)]
With this error:
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 'key, value) VALUES ('ccda78da-689d-4d86-ba72-d65eaf281edf', 'Hello', 'World')' at line 1"}
key is a reserved word.
Try this:
INSERT INTO UserSetting (userId, `key`, value) VALUES (?p0, ?p1, ?p2)
Key is a reserved word, use ticks, example in link
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html