python 关系型数据库mysql存储的简单操作示例

import pymysql
# 创建数据库
# 通过connect方法声明一个mysql链接对象db,然后传入相应的参数
db = pymysql.connect(host = 'localhost',user = 'root',password = 'asdfgh',port = 3306)
# 使用cursor方法获得mysql的操作游标,利用游标来执行sql语句,这里直接用execute()方法
cursor = db.cursor()
cursor.execute('SELECT VERSION()')
# 调用fetchone方法获得第一条数据,得到版本号
data = cursor.fetchone()
print('database version:',data)
cursor.execute('CREATE DATABASE spiders DEFAULT CHARACTER SET utf8')
db.close()

# 创建表
import pymysql
db = pymysql.connect(host = 'localhost',user = 'root',password = 'asdfgh',port = 3306)
# 使用cursor方法获得mysql的操作游标,利用游标来执行sql语句,这里直接用execute()方法
cursor = db.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL,name VARCHAR(255) NOT NULL,age INT NOT NULL,PRIMARY KEY(id))')
db.close()

# 插入数据
import pymysql
id = '0'
user = 'bb'
age = '20'
db = db = pymysql.connect(host = 'localhost',user = 'root',password = 'asdfgh',port = 3306)
cursor = db.cursor()
# 有几个value就写多少个%s
sql = 'INSERT INTO student(id,name,age) values(%s,%s,%s)'
try:
    cursor.execute(sql,(id,user,age))
    # 需要执行db对象的commit方法才可以实现数据插入,更新,删除等,这个方法是真正将语句提交到数据库中执行的方法
    db.commit()
except:
    # 执行rollback方法来进行数据回滚,就当啥也没发生
    db.rollback()
db.close()

# 更新数据
# SQL语句会根据字典动态构造,元组也动态构造,这样才能实现通用的插入方法
data = {
    id :'0',
    user : 'bb',
    age : '20'
}
table = 'student'
keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
# 利用字符串的format方法将表名,字段名,和占位符构造出来
# ON DUPLICATE KEY UPDATE表示的是如果主键已经存在,就执行更新操作,一种比较灵活的去重的方法
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,table(data.values())*2):
        print('successful')
        db.commit()
except:
    print('fail')
    db.rollback()
db.close()

# 删除数据
# 只需要指定要删除的目标表名,删除条件
table = 'student'
condition = 'age' > '20'
sql = 'DELETE FROM {table} WHERE {condition}'.format(table= table,condition = condition)
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()
db.close()

# 查询数据
sql = 'SELECT * FORM student WHERE age >= 20'
try:
    cursor.execute(sql)
    # 调用cursor的rowcount属性获取查询结果的条数
    print('COUNT:',cursor.rowcount)
    one = cursor.fetchone()
    print('one:',one)
    # 调用fetchall方法,得到结果的所有数据,是一个二重元组,但是如果数据量很大的话,占用内存会很大
    # 可以考虑下使用fetchone来以元组的方式返回,每循环一次,指针就会偏移一条数据,随用随取,简单高效
    results = cursor.fetchall()
    print('results:',results)
    for row in results:
        print(row)
except:
    print('error')

猜你喜欢

转载自blog.csdn.net/weixin_41931602/article/details/82730249
今日推荐