首页 > 编程 > Python > 正文

Python3数据库操作包pymysql的操作方法

2019-11-25 14:19:33
字体:
来源:转载
供稿:网友

以下代码实现环境是mac系统,本地配置mysql服务端和navicat premium客户端,python环境是配置了pymysql的anaconda3。

首先,与数据库建立connection和进行操作的原理

这里写图片描述

(1)通过navicat premium创建testdataset数据库和库内数据表test:

CREATE TABLE `test` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(10) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这里写图片描述

(2)在test数据表里添加数据项

这里写图片描述

(3)jupyter notebook里连接数据库,并对数据库进行操作

import pandas as pdimport datetimeimport pymysql#创建连接conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',             passwd='******', db='testdataset', charset='utf8')#passwd是本地mysql服务器密码conn#Output:<pymysql.connections.Connection at 0x11443e588>#创建游标cursor = conn.cursor()cursor#Output:<pymysql.cursors.Cursor at 0x11443e2e8>#执行SQL,并返回受影响行数effect_row = cursor.execute("select * from test")effect_row#Output:4#获取剩余结果的第一行数据r1=cursor.fetchone()r1#Output:(1, '李明', 18)name='王天'age=17sql="select name,age from test where name='%s' and age='%s'" % (name,age)row_count=cursor.execute(sql) row_1 = cursor.fetchone()print(row_count,row_1)#Output:1 ('王天', 17)conn.commit()cursor.close()conn.close()

总结

以上所述是小编给大家介绍的Python3数据库操作包pymysql的操作方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表