python读取sql⽂件-读取.sql⽂件以在Python中执⾏
(pymysql)
我正在尝试创建⼀个多脚本⼯具,该⼯具将使⽤.sql⽂件的参数并执⾏它.
我已经建⽴了⼀个简单的测试,只在⼀个数据库上执⾏,但是语法每次都会给我带来⿇烦.
DELIMITER $$
CREATE DEFINER=`a_user`@`%` PROCEDURE `a_procedure`(
IN DirectEmployeeID TEXT,
IN StartRange DATE,
IN EndRange DATE
)
BEGIN
SELECT aColumn
WHERE thisThing = 1;
END$$
DELIMITER ;
需要明确的是,该脚本已经过测试,可以通过以下⽅式⼯作:
mysql -uuser -p -hhost -Pport databaseName < file.sql
并且也可以通过mysql⼯作台⼯作.
我在另⼀个⽹站上看到了这种解决⽅案:
with conn.cursor() as cursor:
f = sys.argv[1]
file = open(f, "r")
sql = " ".adlines())
python怎么读取py文件ute(sql)
这给了我⼀个MySQL语法错误:
check the manual that corresponds to your MySQL server version for the right
syntax to use near "DELIMITER $$ CREATE DEFINER=`a_user`@`%` PROCEDURE
`MyCommissionsDirect`( IN " at line 1")
如您所见,脚本中包含mysql不喜欢的换⾏符.
然后我尝试了这个:
with conn.cursor() as cursor:
f = sys.argv[1]
file = open(f, "r")
sql = ""
line = adline()
while line:
sql += " " + line.strip(" ").strip(" ")
line = adline()
print sql
并得到另⼀个语法问题,打印结果显⽰这是全部⼀⾏,在mysqlworkbench中不起作⽤.甚⾄没有尝试执⾏它,这很奇怪.
当我先将DELIMETER $$放在单独的⾏上时,它将在mysqlworkbench中执⾏.
这是我可能会变得越来越复杂的情况之⼀.我很惊讶pymysql没有简单地直接执⾏sql⽂件的⽅法.我很疲倦地尝试进⾏字符串操作并使该操作适⽤于特定⽂件,因为那样⼀来,使该⼯具变得模棱两可和可重⽤的梦想就荡然⽆存了.
我会以完全错误的⽅式进⾏此操作吗?
谢谢!
解决⽅法:
这是我在PyMySQL中使⽤SQL⽂件的解决⽅案.这些⽂件包含许多以结尾的请求;⽤于拆分列表中的请求.所以要当⼼失踪;在列表中.
我决定增加失踪者;不在函数中保留for循环.也许有更好的⽅法.
create-db-loff.sql:
DROP DATABASE IF EXISTS loff;
CREATE DATABASE loff CHARACTER SET "utf8";
USE loff;
CREATE TABLE product(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`code` BIGINT UNSIGNED NOT NULL UNIQUE,
`name` VARCHAR(200),
`nutrition_grades` VARCHAR(1)
);
CREATE TABLE category(
`id`INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(200)
);
CREATE TABLE asso_prod_cat(
`category_id` INT UNSIGNED NOT NULL,
`product_id` INT UNSIGNED NOT NULL,
CONSTRAINT `fk_asso_prod_cat_category`
FOREIGN KEY(category_id)
REFERENCES category(id)
ON DELETE CASCADE,
CONSTRAINT `fk_asso_prod_cat_product`
FOREIGN KEY(product_id)
REFERENCES product(id)
ON DELETE CASCADE
)
;
db.py:
DB_CONFIG = {
"host": "localhost",
"user": "loff",
"pass": "loff",
"db": "loff",
"char": "utf8",
"file": "create-db-loff.sql"
}
def get_sql_from_file(filename=DB_CONFIG["file"]): """
Get the SQL instruction from a file
:return: a list of each SQL query whithout the trailing ";" """
from os import path
# File did not exists
if path.isfile(filename) is False:
print("File load error : {}".format(filename))
return False
else:
with open(filename, "r") as sql_file:
# Split file in list
ret = ad().split(";")
# drop last empty entry
ret.pop()
return ret
request_list = _sql_from_file()
if request_list is not False:
for idx, sql_request in enumerate(request_list):
标签:pymysql,python,mysql

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。