Python连接MySQL数据库读取数据实践
安装PyMySQL
pip install PyMySQL
建立测试表
CREATE TABLE `t1` (
`id` bigint(20) NOT NULL Primary key,
`name` varchar(100)
)
添加测试数据
INSERT INTO `t1` VALUES (1, 'A');
INSERT INTO `t1` VALUES (2, 'B');
INSERT INTO `t1` VALUES (3, 'C');
写入数据
import pymysql
#建立与MySQL的连接
conn = pymysql.connect(host='192.168.1.100', port=3306, user='root', password='123456', database='test',autocommit=True)
cursor = conn.cursor()
try:
# 执行SQL语句添加数据
sql = "insert into t1(id,name) values(\"10\",\"E\")"
cursor.execute(sql)
print("添加数据结束")
except Exception as e:
print("Error:", str(e))
finally:
#关闭连接
cursor.close()
conn.close()
查询数据
import pymysql
#建立与MySQL的连接
conn = pymysql.connect(host='192.168.1.100', port=3306, user='root', password='123456', database='test',autocommit=True)
cursor = conn.cursor()
try:
#执行SQL语句查询
sql = "select id,name from t1"
cursor.execute(sql)
#获取结果
results = cursor.fetchall()
for row in results:
print(row)
except Exception as e:
print("Error:", str(e))
finally:
#关闭连接
cursor.close()
conn.close()