安装mysql和sqlServe的python驱动:
安装pymysql:python3 -m pip install pymysql,查看安装后的版本python3 -m pip show pymysql.
安装pymssql:python3 -m pip install pymssql,查看安装后的版本python3 -m pip show pymssql.
由于缺少—mssql,参考解决办法http://blog.csdn.net/HHTNAN/article/details/77931782,我们用第二种解决办法.whl的下载地址为https://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql,装命令为python3 -m pip
install pymssql-2.1.3-cp36-cp36m-win32.whl.查看安装的版本python3 -m pip show pymssql.
数据库连接操作流程和函数介绍:
任何数据库无法避免的就是连接操作,这里mysql和sqlserver的连接传的参数略微有些不同,pymssql.connect(self.host,self.user,self.pwd,self.db,charset="utf8"),sqlserver传的是4个参数,host为ip加端口,用户名,密码,库名,字符编码;而mysql的pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.pwd,db=self.db,charset="utf8")其它都一样,host为IP加上一个独立的端口传参。
查询语句,通过连接后返回的对象conn的cursor的方法创建游标对象cur,调用cur的execute的方法执行sql语句,用fetchone查询单条语句,fetchall查询多条数据。之后调用conn的close方法关闭连接。
非查询语句,通过连接后返回的对象conn的cursor的方法创建游标对象cur,调用cur的execute的方法执行sql语句,然后conn调用commit的方法去提交数据,然后调用close的方法关闭数据库连接。
创建数据库对象和测试例子:
#-*-coding:utf-8-*-s
#mysql和sqlserver的库
import pymysql,pymssql
class Database:
def __init__(self,*db):
if len(db)==5:
#mysql数据库
self.host=db[0]
self.port=db[1]
self.user=db[2]
self.pwd=db[3]
self.db=db[4]
else:
#sqlserver数据库
self.host=db[0]
self.port=None
self.user=db[1]
self.pwd=db[2]
self.db=db[3]
def _Getconnect(self):
if not self.db:
raise NameError+"没有设置数据库信息"
if (self.port==None):
self.conn=pymssql.connect(self.host,self.user,self.pwd,self.db,charset="utf8")
else:
self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.pwd,db=self.db,charset="utf8")
cur=self.conn.cursor()
if not cur:
raise "数据库连接不上"
else:
return cur
#查询sql
def ExecQuery(self,sql):
cur=self._Getconnect()
cur.execute(sql)
relist=cur.fetchall()
self.conn.close()
return relist
#非查询的sql
def ExecNoQuery(self,sql):
cur=self._Getconnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
测试代码:
#sqlserver数据库信息
SqlServerhost="192.168.100.85:12033"
SqlServeruser="AKTEST"
SqlServerpwd="btjf123!"
SqlServerdb="AK_Data_jccs"
#Mysql数据库信息
Mysqlhost="192.168.100.211"
Mysqlport=3307
Mysqluser="akmysql"
Mysqlpwd="mysql123"
Mysqldb="bt_hyaline"
database=Database(SqlServerhost,SqlServeruser,SqlServerpwd,SqlServerdb)
#sqlserver查询
sql="select top 1 * from t_code order by fid desc"
relist=database.ExecQuery(sql)
print (relist)
#sqlserver非查询
sql="update t_code set ftypes=1 where fid=83902"
database.ExecNoQuery(sql)
database=Database(Mysqlhost,Mysqlport,Mysqluser,Mysqlpwd,Mysqldb)
#Mysql查询
sql="select * from t_Bank where fid = 2"
relist=database.ExecQuery(sql)
print (relist)
#Mysql非查询
sql="update t_Bank set FShortName=2 where fid = 2"
database.ExecNoQuery(sql)