0
点赞
收藏
分享

微信扫一扫

Python连接MySQL数据库读取数据实践

阎小妍 03-07 23:00 阅读 2

Python连接MySQL数据库读取数据实践

安装PyMySQL

pip install PyMySQL

Python连接MySQL数据库读取数据实践_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()

Python连接MySQL数据库读取数据实践_PyMySQL_02


举报

相关推荐

0 条评论