generate sql file with python (for mysql) -
i need write in txt file, sql statements values escaped can later import mysql database.
some background info: created program in python reads csv file , inserts data remote mysql database. program except insert statements, performs several select statements in order collect information such primary keys, max ids etc.
what need in general: since whole procedure time consuming hoping there way write statements in .sql file import mysql database via phpmyadmin.
what tried , stuck: far can generate sql statements concatenating text. stuck point need escape characters.
in sql server can include text between n'' , accept is.. there similar in mysql?
example in sql server: n'my escaped text isn't affected single quote ->' or double quote " '
notice have surrounded text n''.
thanks in advance!
you're going want learn how use prepared statements. solve several problems you, including escaping characters , preventing sql injection. here's example mysqldb:
myvalues = (value1, value2) sql = "insert mytable (column1, column2) values (%s, %s)" cursor.execute(sql, myvalues)
===
i'm sorry, think misunderstood question. don't want write python script reads file , inserts data database. want use python generate sql document can import database directly.
i recommend using python query database, if want make sql document, data values need enclosed in single quotes, , if have single quotes in data, escape them using double single quotes:
insert mytable (column1, column2) values ('my data', 'john''s data');
other special characters such semicolon (;) ignored if they're inside single quotes.
if you're worried special characters in table , column names, can add backticks them:
insert `mytable` (`column1`, `column2`) values ('my data', 'john''s data');
Comments
Post a Comment