专注于MySQL数据库,其他数据库都存在相对应的python库,使用方法大同小异。自行百度···
import pymysql
DATA_BASE = {'host': '10.118.XX.XX', 'user': 'root', 'port': 3306, 'password': '#0516#',
'database': 'testfirstroom', 'charset': 'utf8'}
conn = pymysql.connect(**DATA_BASE) # 实例化一个数据操作对象
cursor = conn.cursor() # 实例化游标操作sql语句
sql1 = 'select * from demo_report where id=185465527'
sql2 = 'select * from demo_report'
cursor.execute(sql1) # 执行sql语句
res1 = cursor.fetchall() # 收集SQL语句执行的结果集(多条数据)
cursor.execute(sql2)
res2 = cursor.fetchone() # 当SQL执行结果有多条数据时只取第一条
print('res1:{}'.format(res1))
print('res2:{}'.format(res2))
# conn.commit() # 若执行新增、删除、修改等SQL语句时需要进行数据提交
打印结果
封装一个mysql上下文管理器对象
from pymysql import connect
class MysqlHandle:
def __init__(self, database=None):
self.database = database
def __enter__(self):
self.conn = connect(**self.database)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close()
self.conn.close()
with MysqlHandle(database=DATA_BASE) as f:
f.execute(sql1)
print(f.fetchone())
打印结果: