python3数据库框架_python3之pymysql

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

下载安装pymsql模块

pip3 install pymysql

操作前准备

#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

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.插入数据

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值