安装pymysql
1 |
pip3 install pymysql |
db.py类文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import pymysql class MyDb(): def __init__(self , host="127.0.0.1", user="root", password="root", database="test",charset="utf8"): self.host = host self.user = user self.password = password self.database = database self.cur = None self.con = None # connect to mysql try: self.con = pymysql.connect(host = self.host, user = self.user, password = self.password, database = self.database) self.cur = self.con.cursor(pymysql.cursors.DictCursor) except : raise "DataBase connect error,please check the db config." def close(self): '''结束查询和关闭连接''' self.con.close() def create_table(self,sql_str): '''创建数据表''' try: self.cur.execute(sql_str) except Exception as e: print(e) def sql_read(self,sql_str): '''查询数据并返回 cursor 为连接光标 sql_str为查询语句 ''' try: self.cur.execute(sql_str) rows = self.cur.fetchall() return rows except: return False def sql_write(self,sql): ''' 插入或更新记录 成功返回最后的id ''' self.cur.execute(sql) self.con.commit() return self.cur.lastrowid |
引用db.py文件进行测试
1 2 3 4 5 6 7 |
from db import MyDb mdb = MyDb(database='bot') #mdb.sql_write("update test set data='修改后的数据55' where id=43") datas=mdb.sql_read("select * from replaykeywords") for row in datas: #print(row['word']) |
近期评论