1.pymysql和mysqldb主要区别:mysqldb只支持python2,还不支持3,所以在python3中用pymysql代替
2.使用python脚本实现增删改查和事物处理:
import sysimport pymysql
class dataBase(): global TABLENAME def connectDB(self,sql): try: #连接数据库 conn=pymysql.connect(host="10.20.89.15",port=3306,user="root",password="123456", db="cs-sincerity",charset="utf8") #获取游标 curs=conn.cursor(pymysql.cursors.DictCursor) #执行sql curs.execute(sql) alldatas=curs.fetchall()
if sql.find('insert')>-1: alldatas=conn.insert_id() conn.commit() curs.close() conn.close() return alldatasexcept: print("Can't connect database") sys.exit()
def selectBy(self,column,condition): sql="select "+column+" from "+dataBase.TABLENAME+" where "+condition return self.connectDB(sql)def selectOneBy(self,columns,condition): sql="select "+columns+" from "+dataBase.TABLENAME+" where "+condition data=self.connectDB(sql) if(len(data)==1): return self.connectDB(sql)[0] elif(len(data)==0): print(sql+":未查询到数据") return datadef updateBy(self,value,condition): sql="update "+dataBase.TABLENAME+" set "+value+" where "+condition return self.connectDB(sql)#插入数据,values是各个列的值def insertBy(self,value,condition): sql="insert into "+dataBase.TABLENAME+" "+condition+" values "+value return self.connectDB(sql)def deleteBy(self,condition): sql="delete from "+dataBase.TABLENAME+" where "+condition return self.connectDB(sql)
来源:https://www.cnblogs.com/cici-xf-2019-7-21/p/11223423.html