一、基本操作
1.连接数据库
db = pymysql.connect(host='IP',port=3306,user='端口',password='密码',database='数据库名',charset='utf8')
2.创建游标,操作数据库;
- 查询操作使用
游标.fetchone()
然后print打印出来
cur=con.cursor() #创建游标
sql='select * from student3'
cur.execute(sql) #执行sql
reslut=cur.fetchone() #查询数据 fetchone():查询一条; fetchall():查询所有;fetchmany(指定数字):查询指定条数
print(reslut)
db.close()
- 增加、修改、删除等操作需要在执行sql后使用
db.commit()
语句提交
cur=con.cursor() #创建游标
sql='delete from student3 where id=8'
cur.execute(sql) #执行sql
db.commit()
db.close() #关闭连接
二、代码封装
- ini文件
- 代码封装,解析ini文件需要用到 configparser库
import configparser
import pymysql
# 获取配置文件里面的数据 MySqlDB('db.ini','Test_db')
class MySqlDB:
# 读取配置文件里面的数据,在放到连接中连接数据库
def __init__(self,configpath,db):
"""
解析ini配置文件,创建连接、创建游标
:param configpath: ini文件路径
:param db: ini文件中的哪个配置连接
"""
config=configparser.ConfigParser()
config.read(configpath)
# 读取文件数据
host=config[db]['host']
port=int(config[db]['port'])
user=config[db]['user']
password=config[db]['password']
database=config[db]['database']
charset=config[db]['charset']
#创建连接
self.db=pymysql.connect(host=host, port=port, user=user, password=password, database=database,
charset=charset)
# 创建游标
self.cur = self.db.cursor()
#关闭连接、关闭游标
def close(self):
self.cur.close()
self.db.close()
#封装查询sql
def get_all(self,sql):
ret=None
try:
self.cur.execute(sql)
ret=self.cur.fetchall()
self.close()
except Exception as e:
print(e)
return ret
#封装编辑sql
def edit(self,sql):
try:
self.cur.execute(sql)
self.db.commit()
self.close()
except Exception as e:
print(e)
return True
if __name__ == '__main__':
my = MySqlDB('db.ini','Test_db')
print(my.get_all('select * from student3'))