python3使用pymysql模块,连接mysql数据库,实现新增、查询和更
1、环境数据准备: python3环境、pymysql模块 mysql数据库:本次代码中用到的数据库为本地的testdb数据库,user表(表字段比较简单,只有主键id,手机号mobile,密码passwd) 2、本次代码直接封装为类,代码中附有注释,把数据库参数改为自己实际的就可以直接使用 ? 1 #引入pymysql模块 2 import pymysql 3 4 class DoMysql: 5 #初始化 6 def __init__(self): 7 #创建连接 8 self.conn = pymysql.Connect( 9 host = 'localhost',10 port = 3306,11 user = 'root',12 password = 'root',13 db = 'testdb',14 charset = 'utf8',15 cursorclass = pymysql.cursors.DictCursor #以字典的形式返回数据 16 ) 17 #获取游标 18 self.cursor = self.conn.cursor() 19 20 #返回多条数据 21 def fetchAll(self,sql): 22 self.cursor.execute(sql) 23 return self.cursor.fetchall() 24 25 #插入一条数据 26 def insert_one(self,sql): 27 result = self.cursor.execute(sql) 28 self.conn.commit() 29 return result 30 31 #插入多条数据 32 def insert_many(self,sql,datas): 33 result = self.cursor.executemany(sql,datas) 34 self.conn.commit() 35 return result 36 37 #更新数据 38 def update(self,sql): 39 result = self.cursor.execute(sql) 40 self.conn.commit() 41 return result 42 43 #关闭连接 44 def close(self): 45 self.cursor.close() 46 self.conn.close() 47 48 49 50 51 if __name__ == '__main__': 52 mysql = DoMysql() 53 #插入一条数据 54 sql = 'insert into `user`(`mobile`,`passwd`) values("13100010000","123456")' 55 result = mysql.insert_one(sql) 56 print(result) #返回插入数据的条数(1) 57 58 #插入多条数据 59 datas = [ 60 ("13100010001","222221"),61 ("13100010002","666666") 62 ] 63 sql = 'insert into `user`(`mobile`,`passwd`) values(%s,%s)' 64 result = mysql.insert_many(sql,datas) 65 print(result) #返回插入数据的条数(2) 66 67 #查询数据 68 sql = 'select * from user' 69 result = mysql.fetchAll(sql) #返回列表,如果多条数据,列表中嵌套字典 70 for item in result: 71 print(item.get('mobile')) #循环列表,输出mobile值 72 73 #关闭连接 74 mysql.close() ?
pymysql.Connect()参数说明 connection对象支持的方法 cursor对象支持的方法 ?
? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |