网络编程
位置:首页>> 网络编程>> 数据库>> Python3数据库操作包pymysql的操作方法

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

作者:Young_id  发布时间:2024-01-28 20:01:34 

标签:python,pymysql,数据库,操作包

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

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

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

(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;

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

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

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

(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()

总结

以上所述是小编给大家介绍的Python3数据库操作包pymysql的操作方法网站的支持!

来源:https://blog.csdn.net/cymy001/article/details/81049493

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com