分类: Python/Ruby
2021-05-19 17:24:34
具体连接、测试代码:
# server默认为127.0.0.1,如果打开了TCP动态端口的需要加上端口号,如'127.0.0.1:1433'
# user默认为sa
# password为自己设置的密码
# database为数据库名字
server = '127.0.0.1'
user = "sa"
password = "123456"
database = "pubs"
conn = pymssql.connect(server, user, password, database)
# 可简化为conn = pymssql.connect(host='localhost', user='sa', password='123456', database='pubs')
cursor = conn.cursor()
cursor.execute('SELECT * FROM titles')
print( cursor.fetchall() )
# 如果用pandas读取数据库
import pymssql
import pandas as pd
conn = pymssql.connect('IP地址','账号','密码','数据库')
sql_1 = "SELECT Id,creat_time from 表名"
#利用pandas直接获取数据"
data = pd.read_sql(sql_1, conn)
conn.close()
print(data)
封装好的版本:
#coding=utf-8
# sqlserver的连接
import pymssql
class MSSQL:
def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
def __GetConnect(self):
"""
得到连接信息
返回: conn.cursor()
"""
if not self.db:
raise(NameError,"没有设置数据库信息")
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
cur = self.conn.cursor()
if not cur:
raise(NameError,"连接数据库失败")
else:
return cur
def ExecQuery(self,sql):
"""
执行查询语句
返回的是一个包含tuple的list货币代码,list的元素是记录行,tuple的元素是每行记录的字段
"""
cur = self.__GetConnect()
cur.execute(sql)
resList = cur.fetchall()
#查询完毕后必须关闭连接
self.conn.close()
return resList
def ExecNonQuery(self,sql):
"""
执行非查询语句
调用示例:
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
"""
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
def main():
# host默认为127.0.0.1,如果打开了TCP动态端口的需要加上端口号,如'127.0.0.1:1433'
# user默认为sa
# pwd为自己设置的密码
# db为数据库名字
ms = MSSQL(host='127.0.0.1',user="sa",pwd="123456",db="pubs")
resList = ms.ExecQuery("SELECT * FROM titles")
print(resList)
if __name__ == '__main__':
main()