当前位置:主页 > 软件编程 > Python代码 >

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

时间:2021-03-21 10:31:34 | 栏目:Python代码 | 点击:

以下代码实现环境是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 pd
import datetime
import 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=17
sql="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()

总结

您可能感兴趣的文章:

相关文章