python3操作mysql数据库的方法
软硬件环境
OSXEICapitan
Python3.5.1
mysql5.6
前言
在开发中经常涉及到数据库的使用,而python对于数据库也有多种解决方法。本文以python3中的mysql为例,介绍pymysql模块的使用。
准备数据库
创建一个mysql数据库,名字叫testdb,建立一张表叫testtable,它有3个字段,分别是id,数据类型是INT(11),设为主键、非空、UNSIGNED、AUTOINCREMENT,name,数据类型是VARCHAR(45),设为非空、唯一,sex,数据类型是VARCHAR(45),设为非空
python3源码
#-*-coding:utf-8-*-
__author__='djstava@gmail.com'
importlogging
importpymysql
classMySQLCommand(object):
def__init__(self,host,port,user,passwd,db,table):
self.host=host
self.port=port
self.user=user
self.password=passwd
self.db=db
self.table=table
defconnectMysql(self):
try:
self.conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.password,db=self.db,charset='utf8')
self.cursor=self.conn.cursor()
except:
print('connectmysqlerror.')
defqueryMysql(self):
sql="SELECT*FROM"+self.table
try:
self.cursor.execute(sql)
row=self.cursor.fetchone()
print(row)
except:
print(sql+'executefailed.')
definsertMysql(self,id,name,sex):
sql="INSERTINTO"+self.table+"VALUES("+id+","+"'"+name+"',"+"'"+sex+"')"
try:
self.cursor.execute(sql)
except:
print("insertfailed.")
defupdateMysqlSN(self,name,sex):
sql="UPDATE"+self.table+"SETsex='"+sex+"'"+"WHEREname='"+name+"'"
print("updatesn:"+sql)
try:
self.cursor.execute(sql)
self.conn.commit()
except:
self.conn.rollback()
defcloseMysql(self):
self.cursor.close()
self.conn.close()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。