前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3之pymysql

python3之pymysql

作者头像
py3study
发布2020-01-03 17:56:40
4220
发布2020-01-03 17:56:40
举报
文章被收录于专栏:python3

pymsqlPython中操作MySQL的模块并且只有在Python3.0版本中才存在,其使用方法和MySQLdb几乎相同

下载安装pymsql模块

代码语言:javascript
复制
pip3 install pymysql

操作前准备

代码语言:javascript
复制
#1.创建数据库
mysql> create database mydb;
mysql> use mydb;

#2.创建表
create table students
    (
        id int  not null auto_increment primary key,
        name char(8) not null,
        sex char(4) not null,
        age tinyint unsigned not null,
        tel char(13) null default "-"
    );

#3.插入两条数据
mysql> insert  into students values(1,"jack","M",20,"stu");
mysql> insert  into students values(2,"xander","M",20,"stu");

1.执行SQL

代码语言:javascript
复制
import pymysql

# 创建mysql连接(socket),client --> server
"""
host = "Server端IP"
port = "Server端口"
user = "Server端用户"
passwd = "Server端密码"
db = "Server端数据库名"
"""
conn = pymysql.connect(host="10.0.0.51",port=3306,user="root",passwd="123456",db="mydb")

#创建游标(光标位置),相当于是socket上的实例
cursor = conn.cursor()

# 执行SQL语句,并返回受影响的行数
"""
cursor.execute("需要执行的sql语句")
"""
effect_row = cursor.execute("select * from students")
print(cursor.fetchone())    # 获取第一条数据
print(cursor.fetchone())    # 获取第二条数据
print("------")
print(cursor.fetchall())    # 获取所有数据(从未被获取的数据中读出来)

# 提交SQL语句执行结果,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()

# 关闭MySQL连接
conn.close()

2.插入数据

代码语言:javascript
复制
import pymysql

# 创建mysql连接(socket),client --> server
conn = pymysql.connect(host="10.0.0.51",port=3306,user="root",passwd="123456",db="mydb")

#创建游标(光标位置),相当于是socket上的实例
cursor = conn.cursor()

# 定义需要插入的数据
data = [
    ("Daniel","M","21","stu"),
    ("Noah","M","25","stu"),
    ("David", "M", "25", "stu")
]

# 执行插入SQL语句
cursor.executemany("insert into students(name,sex,age,tel) values(%s,%s,%s,%s)" ,data)

# 提交SQL语句执行结果,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()

# 关闭MySQL连接
conn.close()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档