介绍

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

安装

pip install pymysql

  

本地数据库操作

mysql> create database mydb1;
#Query OK, 1 row affected

mysql> use mydb1;
#Database changed

mysql> create table users(
    -> id int not null auto_increment primary key,
    -> name char(8) not null,
    -> age tinyint unsigned not null,
    -> sex char(4) not null,
    -> tel char(13) null default "-"
    -> );
#Query OK, 0 rows affected

mysql> commit;
#Query OK, 0 rows affected

  

基本操作

import pymysql
# 连接mysql
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb1')

# 获取游标
cur = conn.cursor()

try:
    # 使用execute执行sql语句
    reCount = cur.execute('select * from users;')
    # reCount = cur.execute('insert into users(name,age,sex) values(%s,%s,%s)', ('momo', '13','male'))
    # reCount = cur.execute('insert into users(name,age,sex) values(%(age)s, %(name)s, %(sex)s)',{'sex':'female,'name':'pig','age':10})

    
    # 使用fetchone 获取一条数据
    data = cur.fetchone()
    
    # 使用fetchall 获取所有数据
    #data = cur.fetchall()
    
    # 提交命令
    conn.commit()
except:
    # 发生错误回滚
    conn.rollback()

# 关闭游标
cur.close()

# 关闭数据库连接
conn.close()
  
print(reCount)
print(data)

  

创建数据库表

 1 #!/usr/bin/python3
 2 
 3 import pymysql
 4 
 5 # 打开数据库连接
 6 db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 7 
 8 # 使用 cursor() 方法创建一个游标对象 cursor
 9 cursor = db.cursor()
10 
11 # 使用 execute() 方法执行 SQL,如果表存在则删除
12 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
13 
14 # 使用预处理语句创建表
15 sql = """CREATE TABLE EMPLOYEE (
16          FIRST_NAME  CHAR(20) NOT NULL,
17          LAST_NAME  CHAR(20),
18          AGE INT,  
19          SEX CHAR(1),
20          INCOME FLOAT )"""
21 
22 cursor.execute(sql)
23 
24 # 关闭数据库连接
25 db.close()
创建数据库表

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-08
  • 2021-05-23
  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-27
  • 2021-09-15
  • 2021-05-27
  • 2022-12-23
  • 2021-10-08
  • 2022-02-26
相关资源
相似解决方案