Lancer un script sql dans un fichier *.sql
Bonjour à tous,
J'ai essayé de lancer un script .sql via la classe suivante mais toujours en vain !
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
# encoding=utf8
import sys
import mysql.connector
import re
class ExecuteSqlFile:
def ExecuteSQl(self,filename,user, password, port, host):
reload(sys)
sys.setdefaultencoding('utf8')
f = open(filename, 'r')
cnx = mysql.connector.connect(user=user, password=password, port=port,
host=host)
cursor = cnx.cursor()
query = " ".join(f.readlines())
query1= self.remove_comments(query)
for result in cursor.execute(query1, multi=True):
pass
cnx.commit()
cnx.close()
cnx.disconnect()
def remove_comments(self,string):
pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)"
# first group captures quoted strings (double or single)
# second group captures comments (//single-line or /* multi-line */)
regex = re.compile(pattern, re.MULTILINE|re.DOTALL)
def _replacer(match):
# if the 2nd group (capturing comments) is not None,
# it means we have captured a non-quoted (real) comment string.
if match.group(2) is not None:
return "" # so we will return empty to remove the comment
else: # otherwise, we will return the 1st group
return match.group(1) # captured quoted-string
return regex.sub(_replacer, string)
if __name__=="__main__":
exsql=ExecuteSqlFile()
exsql.ExecuteSQl('C:\creation_DB.sql','root', '***', '3306', 'localhost') |
et voilà l'erreur que j'ai eu:
Code:
1 2 3 4 5 6 7 8 9
|
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ';
UNLOCK TABLES;
--
-- Table structure for table `hs_org`
--
DROP TABLE' at line 1 |
Cependant, le code tourne très bien que je le lance avec MySQL Workbench.
Merci beaucoup d'avance !