当前位置: 首页 > 后端技术 > Python

Python3操作MySQL

时间:2023-03-25 20:40:52 Python

importpymysql#开启数据库连接db=pymysql.connect(host='localhost',user='root',password='root',database='test')#查询SQL版本#像if,while,def和class的的复合语句,第一行以关键字开头,以冒号(:)结尾,此行之后的一行或多行代码组成一个代码组。defsearchVersion():#使用cursor()方法创建游标对象cursorcursor=db.cursor()#使用execute()方法执行SQL查询cursor.execute("SELECTVERSION()")#使用fetchone()方法获取单条数据。data=cursor.fetchone()print("Databaseversion:%s"%data)#关闭数据库连接db.close()#SQLinsertstatement#Python通常在一行中写一条语句,但是如果语句很长,我们可以使用反斜杠\来实现多行语句defInsertSql(sql):#sql="""INSERTINTOEMPLOYEE(FIRST_NAME,#LAST_NAME,AGE,SEX,INCOME)#VALUES('Mac','Mohan',20,'M',2000)"""try:#使用cursor()方法创建游标对象cursorcursor=db.cursor()#执行sql语句cursor.execute(sql)#提交到数据库执行db.commit()except:#出错则回滚db.rollback()#关闭数据库连接db.close()#SQL查询语句defSearchSql(sql):#sql="SELECT*FROMEMPLOYEE\#WHEREINCOME>100"try:#使用cursor()方法创建游标对象cursorcursor=db.cursor()#执行SQL语句cursor.execute(sql)#获取所有记录列表results=cursor.fetchall()forrowinresults:fname=row[0]lname=row[1]age=row[2]sex=row[3]income=row[4]#打印结果print("fname=%s,lname=%s,age=%s,sex=%s,income=%s"%\(fname,lname,age,sex,income))except:print("Error:unabletofetchdata")#关闭数据库连接db.close()#SQL更新语句defupdateSql(sql):#sql="UPDATEEMPLOYEESETAGE=AGE+1WHERESEX='%c'"%('M')try:cursor=db.cursor()#执行SQL语句cursor.execute(sql)#提交给数据库执行db.commit()except:#出错时回滚发生db.rollback()#关闭数据库连接db.close()#SQL删除语句defDeleteSql(sql):#sql="DELETEFROMEMPLOYEEWHEREAGE>%s"%(20)try:cursor=db.cursor()#执行SQL语句游标.execute(sql)#提交修改db.commit()except:#出错回滚db.rollback()#关闭连接db.close()#查询sqlsqlStr="SELECT*FROMEMPLOYEEWHEREINCOME>100"SearchSql(sqlStr)