Connector for python

PyMySQL安装:

pip install pymysql

连接数据库:

基本操作:

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 1.得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 2.得到一个可以执行SQL语句并且将结果作为字典返回的游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定义要执行的SQL语句 
sql = """CREATE TABLE USER1 ( id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL )ENGINE=innodb
DEFAULT CHARSET=utf8; """
# 执行SQL语句
cursor.execute(sql)

# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()

增删改查操作:

增:
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);" username = "Alex" age = 18

插入数据失败回滚:
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 执行SQL语句
    cursor.execute(sql, [username, age])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()

获取插入数据ID:
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 执行SQL语句
    cursor.execute(sql, [username, age])
    # 提交事务
    conn.commit()
    # 提交之后,获取刚插入的数据的ID
    last_id = cursor.lastrowid
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()

删:
sql = "DELETE FROM USER1 WHERE id=%s;"

改:
sql = "UPDATE USER1 SET age=%s WHERE name=%s;"
username = "Alex"
age = 80
try:
    # 执行SQL语句
    cursor.execute(sql, [age, username])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()

查:
# 查询数据的SQL语句
sql = "SELECT id,name,age from USER1 WHERE id=1;"
# 执行SQL语句
cursor.execute(sql)
# 获取单条查询数据
ret = cursor.fetchone() 
 
posted @ 2019-05-06 16:30  崇州周柏豪  阅读(156)  评论(0编辑  收藏  举报