Is there any ways to run .sql(sql server) file in python?
Python Code:
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())
Below contain is available in test.sql
This sql script is running manually successfully.
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)
)