python调用数据库基本操作(pymysql)

python调用数据库基本操作(pymysql)

mysql >>> pysql

操作 pymysql

如何创建?

pymysql 库的操作基于sql语言
cursor.execute("sql语句")

在一切开始之前要先连接数据库,创建游标cursor,后面的操作都基于cursor

import pymsql
db = pymysql.connect(host="localhost", user="root", password="******", port=3306)
cursor = db.cursor()

创建数据库 spiders
指定默认编码Default CHARACTER SET utf8

cursor.execute("CREATE DATABASE spiders DEFAULT CHARACTER SET utf8")

在数据库中建立表
CREATE TABLE 表名 (列1 数据类型, ..., PRIMARY KEY (主键列))

sql = "CREATE TABLE students (id VARCHAR(254) NOT NULL, name VARCHAR(254) NOT NULL, age INT NULL, PRIMARY KEY (id))"
cursor.execute(sql)

动态添加数据

对于字典类型的数据,可分解插入数据库
并用try...except结构保证成功
sql语句:INSERT INTO students (id, name, age) VALUES (%s, %s, %s)

data = {
    "id": "100001",
    "name": "claire",
    "age": "20"
}
table = "students"
keys = ", ".join(data.keys())
values = ", ".join([%s]*len(data))
sql = "INSERT INTO {table} ({keys}) VALUES ({VALUES})" .format(table=table, keys=keys, values=values)

try:
    if cursor.execute(sql, tuple(data.values()))
    print("Congrats")
    db.commit()
except:
    print("Failed")
    db.rollback()

添加与更新结合

稍稍修改sql语句:先尝试添加,遇到主键存在,就更新
sql语句为:INSERT INTO students (id, name, age) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE id = %s, name = %s, age = %s

data = {
    "id": "20100002",
    "name": "claire",
    "age": "20"
}
table = "students"
keys = ", ".join(data.keys())
values = ", ".join(["%s"]*len(data))
sql = "INSERT INTO {table} ({keys}) VALUES ({VALUES}) ON DUPLICATE KEY UPDATE" .format(table=table, keys=keys, values=values)
update = ", ".join(["key = %s" .format(key=key) for key in data])
sql += update

try:
    if cursor.execute(sql, tuple(data.values())*2):
        print("Congrats")
        db.commit()

except:
    print("Failed")
    db.rollback()

逐条读取数据

fetchone()一次读一条, 读完指针就移到下一条
cursor.fetchall()可以一次把结果放在一个元组里,但占用大

sql = "SELECT * FROM students WHERE age >= 20"

try:
    cursor.execute(sql)
    print("count:", cursor.rowcount)
    row = cursor.fetchone()
    while row:
        print("Row:", row)
        row = cursor.fetchone()
except:
    print(error)

删除数据

table = "students"
condition = "age >20"

sql = "DELETE FROM {table} WHERE {condition}". format(table=table, condition=condition)

try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

你可能感兴趣的:(python调用数据库)