簡體   English   中英

如何在python中運行.sql(mssql或sql服務器)文件?

[英]how to run .sql (mssql or sql server) file in python?

python中有什么方法可以運行.sql(sql server)文件嗎?

Python 代碼:

import pyodbc,tempfile,os
server_name = "localhost"
db_name = "abc"
password = "1234"
local_path = tempfile.gettempdir()
sqlfile = "test.sql"
filepath = os.path.join(local_path,sqlfile)
Connection_string = 'Driver={ODBC Driver 17 for SQL Server};Server='+server_name+';Database='+db_name+';UID=sa;PWD='+password+';'
cnxn = pyodbc.connect(Connection_string)
cursor1 = cnxn.cursor()
with open(filepath, 'r') as sql_file:
        cursor1.execute(sql_file.read())

下面包含在 test.sql 中可用
這個 sql 腳本手動運行成功。

IF EXISTS (SELECT * FROM sys.tables WHERE name = 'area' AND type = 'U') DROP TABLE area;
CREATE TABLE area (
  areaid int NOT NULL default '0',
  mapid int NOT NULL default '0',
  areaname varchar(50) default NULL,
  x1 int NOT NULL default '0',
  y1 int NOT NULL default '0',
  x2 int NOT NULL default '0',
  y2 int NOT NULL default '0',
  flag int NOT NULL default '0',
  restart int NOT NULL default '0',
  PRIMARY KEY  (areaid)
)

你沒有指向正確的位置。

您的文件filepath計算結果類似於C:\TEMP\test.sql (參見tempfile.gettempdir docs

如果將其設置為D:\test\test.sql (來自您的評論),那么它應該可以工作。

import pyodbc

server_name = "localhost"
db_name = "abc"
password = "1234"

connection_string = 'Driver={ODBC Driver 17 for SQL Server};Server='+server_name+';Database='+db_name+';UID=sa;PWD='+password+';'

filepath = r"D:\test\test.sql"  # raw string (r"") to avoid double blackslash

cnxn = pyodbc.connect(connection_string)

cursor1 = cnxn.cursor()

with open(filepath, 'rt') as sql_file:  # note also mode is "rt" to read text
    cursor1.execute(sql_file.read())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM