python通过pymysql连接mysql数据库
2023-09-11 14:16:28 时间
先准备一张测试表:
CREATE TABLE `A` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
数据库表里添加测试用的数据:
![](https://img-blog.csdnimg.cn/img_convert/2d06e4e0867e0f9e962bd77195de9725.png)
测试demo:
#!/usr/bin/python3
# coding=utf-8
import pymysql
mysql_conn = pymysql.connect(
host='192.168.1.66',
port=3306,
user='root',
password='root',
database='xwftest',
charset='utf8',
autocommit=True,
)
print(mysql_conn)
cursor = mysql_conn.cursor() # 结果是元组形式
rows = cursor.execute('select * from A')
print('rows:', rows)
res = cursor.fetchall()
print(res)
cursor.close()
cursor = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor) # 结果是dict形式
cursor.execute('select * from A')
res = cursor.fetchall()
print(res)
print('第一个数据:', res[0]['id'], res[0]['name'], res[0]['age'])
cursor.execute('select * from A where id > %s and id < %s', (2, 5))
print(cursor.fetchall())
cursor.execute('desc A')
for x in cursor.fetchall():
print('字段:', x)
cursor.close()
mysql_conn.close()
运行结果:
![](https://img-blog.csdnimg.cn/img_convert/95c15fb82b28e19da1ace40187817985.png)
相关文章
- MySQL Binlog Digger 4.28 【mysql日志分析工具】
- 【MySQL高级】应用优化及Mysql中查询缓存优化以及Mysql内存管理及优化
- 【MySQL高级】MySql中常用工具及Mysql 日志
- Can‘t connect to local MySQL server through socket ‘/tmp/mysql.sock‘ (2)
- 【零基础学python】:清华官方出品的《看漫画学Python》全彩PDF,495页资源分享
- 35岁了转行python可以吗?什么样的人合适学习Python?
- windows python flask与mysql数据库写入查询
- Python使用MySQL数据库从入门到精通
- 《python 与数据挖掘 》一 第2章 Python基础入门
- 【MySQL进阶-04】深入理解mysql事务本质(超级详解)
- 源码编译vi过程中进行配置时报“checking if compile and link flags for Python are sane... no: PYTHON DISABLED”怎么办?
- Python编程-数据库-利用PyMysql访问windows下的MySql数据库
- 【MySQL】如何向mysql数据库插入当前时间
- 项目访问mysql时报: Failed to obtain JDBC Connection...:Host ‘X‘is not allowed to connect to this MySQL ser
- 【mysql报错】ERROR 2002 (HY000): Can‘t connect to local MySQL server through socket ‘/tmp/mysql.sock‘
- JDBC 连接 MySQL 异常:com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Public Key Retrieval is not allowed
- mac ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
- Python MySQL 数据库连接不同方式
- [mysql]MySQL数据库如何导出
- python操作mysql数据库系列-操作MySql数据库(一)
- Python 使用PyMySql 库 连接MySql数据库时 查询中文遇到的乱码问题(实测可行) python 连接 MySql 中文乱码 pymysql库
- mysql—MySQL数据库中10位或13位时间戳和标准时间相互转换
- Python 基础 之 python 线程知识点整理,并实现一个简单多线程 udp 聊天应用
- python操作mysql数据库
- (19)python操作mysql,python与mysql交互(pymysql)
- Selenium4 Python实现Page Factory设计模式,python新的定位方法
- 【C#】使用MySql.Data.dll连接MySQL数据库
- python封装一个工具类 ,对MySQL数据库增删改查,可多字段动态插入mysql数据库中
- python连接mysql数据库把取数据存入数据库