python3 connect to sql server database and execute simple sql

Python3 connects to the database, first download the pymssql library that connects to the sql server database.

It is very simple to connect to the database with Python, and there are many libraries available. I use the more commonly used pymssql.

Connect to the database: connect = pymssql.connect(self.url, self.username, self.password, self.databaseName);

Get the cursor: cursor = connect.cursor() #The cursor is used to perform sql operations

Query operation: cursor.execute(“select * from t_table”)         
                  rows = cursor.fetchall() #Get the queried data, rows is a tuple type.

Addition, deletion and modification operations: cursor.execute(sql)
                     connect.commit() #Note to submit
          

Paste the code below. I create a database operation object to facilitate the operation of the database. Simple operations include querying all table names in the database, passing in the table name to get all the field names of the table, and executing sql. The code is as follows,

import pymssql
import time
import traceback, sys


def log(str):
	str = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + ':' +str
	with open('file1.txt', 'a+') as f:
		f.write(str)
		f.write('\n')


class database(object):
	"""数据库操作对象"""
	def __init__(self, url,username,password,databaseName):
		
		self.url = url
		self.username = username
		self.password = password
		self.databaseName = databaseName
		self.connect = self.sql_server_conn()
		self.cursor = self.connect.cursor()
		
	def sql_server_conn(self):
		connect = pymssql.connect(self.url,self.username,self.password,self.databaseName) #服务器名,账户,密码,数据库名
		if connect:
			print("连接成功!")
		return connect

	#查看表的所有字段,
	#@table_name :表名
	def get_column_name(self,table_name):
		self.cursor.execute("select top 1 * from " + table_name)   #执行sql语句
		data_dict=[]
		for field in self.cursor.description:
			data_dict.append(field[0])
		print('%s表中有%d个字段'%(table_name,len(data_dict)))
		print(data_dict)
		return data_dict

	#得到数据库所有的表名
	def get_table_name(self):
		sql = "SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U' ORDER BY NAME"
		self.cursor.execute(sql)  # 返回执行成功的结果条数
		rows = self.cursor.fetchall()
		print('共有%d个表'%(len(rows)))
		for d in rows:
			for k in d:
				print(k)

	#执行sql语句,增删改查
	#@sql:sql语句
	def execute_sql(self,sql):
		sql = sql.lower()
		if 'insert' in sql or 'delete' in sql or  'update' in sql:
			try:
				self.cursor.execute(sql)
				self.connect.commit()
				str =  '插入或更新或删除sql:'+sql
				log(str)
				return ;
			except Exception as err:
				str = traceback.format_exc()
				log(str)
		elif 'select' in sql :
			self.cursor.execute(sql)
			rows = self.cursor.fetchall()
			print('共有%d条记录'%(len(rows)))
			for k  in rows:
				print(k) 
			return rows

	#关闭游标,连接
	def close(self):
		self.cursor.close()   #关闭游标
		self.connect.close()


if __name__ == '__main__':
	test = database('url地址', '用户名', '密码', '数据库名')
	test.get_column_name("表名")
	test.get_table_name()
	sql = "select * from t_table"
	test.execute_sql(sql)
	test.close()
	

Guess you like

Origin blog.csdn.net/Xu_programmer/article/details/103993847