Python操作MySQL基础使用
python
import pymysql
# 链接数据库
conn = pymysql.connect(
host='10.5.6.250',
port=3306,
user='root',
password='********'
)
# 查看MySQL版本信息
print(conn.get_server_info()) # 5.5.27
# 获取到游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db("hanligang_data")
# 使用游标对象执行sql语句
sql = "select * from tstudent"
cursor.execute(sql)
# 获取查询结果
results: tuple = cursor.fetchall()
print(results) # 结果是一个大元组,里面包含了每一行数据的小元组
for r in results:
print(r)
conn.close() # 关闭
查询结果(里面身份证为for循环生产的虚拟数据):
python
('0000000118', '魏欣若', '男', '6968390833530048', '1984-09-19 00:00:00.000', 'weixinruo@91xueit.com', '开发', '2019-12-18 17:58:52.85')
('0000000119', '胡辉香', '男', '1687819817472568', '1985-02-18 00:00:00.000', 'huhuixiang@91xueit.com', '开发', '2019-12-18 17:58:52.85')
('0000000120', '姜利维', '男', '1367699597056572', '1988-10-17 00:00:00.000', 'jiangliwei@91xueit.com', '网络', '2019-12-18 17:58:52.85')
('0000000121', '马文霞', '男', '2921194355462422', '1984-03-11 00:00:00.000', 'mawenxia@91xueit.com', '测试', '2019-12-18 17:58:52.85')
('0000000122', '于爽轮', '女', '3826182221042389', '1981-03-27 00:00:00.000', 'yushuanglun@91xueit.com', '网络', '2019-12-18 17:58:52.85')
('0000000123', '吴军雪', '女', '361896711952425', '1988-10-05 00:00:00.000', 'wujunxue@91xueit.com', '开发', '2019-12-18 17:58:52.85')
('0000000124', '廖菲以', '男', '6206075708967862', '1984-10-07 00:00:00.000', 'liaofeiyi@91xueit.com', '开发', '2019-12-18 17:58:52.85')
('0000000125', '孔国馨', '男', '6196758315299228', '1984-04-07 00:00:00.000', 'kongguoxin@91xueit.com', '开发', '2019-12-18 17:58:52.85')
('0000000126', '李伟伟', '女', '9973233711794250', '1988-08-05 00:00:00.000', 'liweiwei@91xueit.com', '开发', '2019-12-18 17:58:52.85')