import sql_connect
def main():
# check if db exists on target, if not create
qry_create_db = "if not exists(select * from sys.databases where name = '{}') create database {};".format('mydb','mydb')
with sql_connect.conn:
cur1 = sql_connect.cursor.execute(qry_create_db)
cur1.commit()
main()
def creation_table(filename):
# Open and read the file as a single buffer
fd = open(filename, 'r')
sqlFile = fd.read()
fd.close()
# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')
# Execute every command from the input file
for command in sqlCommands:
with sql_connect.conn:
cur2 = sql_connect.cursor.execute(command)
cur2.commit()
creation_table('Mypath\\schema\\TABLES\\TOSHBA.sql')
creation_table('Mypath\\schema\\TABLES\\TALM_TYPE.sql')
这是创建我的数据库和表的python代码。问题是当我执行函数
时
"creation_table('Mypath\\schema\\TABLES\\TALM_TYPE.sql')"
我收到此错误:
pyodbc.Error :(“ HY090”,“ [HY090] [Microsoft] [ODBC驱动程序管理器]无效的字符串或缓冲区长度(0)(SQLExecDirectW)”)
这是我的第一个sql文件脚本TOSHBA,我先使用函数creation_table执行,但没有任何错误:
USE mydb;
DROP TABLE IF EXISTS TOSHBA;
CREATE TABLE TOSHBA
(
TOSHBA_WORK_ID INT NOT NULL IDENTITY,
WORK_NAME NVARCHAR(200) NOT NULL,
CONSTRAINT PK_TOSHBA PRIMARY KEY (TOSHBA_WORK_ID)
);
这是我遇到错误的第二个sql脚本文件:
USE mydb;
DROP TABLE IF EXISTS TALM_TYPE;
CREATE TABLE TALM_TYPE
(
TALM_ID INT NOT NULL IDENTITY,
TOSHBA_id INT NOT NULL,
TALM_NAME NVARCHAR(20) NOT NULL,
CONSTRAINT PK_TALM PRIMARY KEY (TALM_ID),
CONSTRAINT FKֹ_TOSHBA_id FOREIGN KEY (TOSHBA_id) REFERENCES TOSHBA (TOSHBA_WORK_ID)
);
请帮助我理解该错误并找到解决方法。
Python版本:3.7.3 Pyodbc版本:4.0.27