Python操作Mysql数据库

连接数据库

import pymysql

db = pymysql.connect(host='localhost',user='root', password='123456', port=3306)
cursor = db.cursor()
cursor.execute('SELECT VERSION()')
data = cursor.fetchone()
print('Database version:', data)
db.close()

创建数据库

import pymysql

db = pymysql.connect(host='localhost',user='root', password='root', port=3306)
cursor = db.cursor()
cursor.execute("CREATE DATABASE demo DEFAULT CHARACTER SET utf8")
db.close()

创建表

import pymysql

db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='demo')
cursor = db.cursor()
sql = 'CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id))'
cursor.execute(sql)
db.close()

插入数据

import pymysql

id = '10'
name = 'zhang'
age = 18

db = pymysql.connect(host='localhost', user='root', password='root', port=3306, db='demo')
cursor = db.cursor()
sql = 'INSERT INTO students(id, name, age) values(%s, %s, %s)'
try:
    cursor.execute(sql, (id, name, age))
    db.commit()
except:
    db.rollback()
db.close()

事务机制,一旦出错会回滚,不存在一半插入一半没插入的情况。

更新数据

sql = 'UPDATE students SET age = %s WHERE name = %s'
try:
   cursor.execute(sql, (30, 'zhang'))
   db.commit()
except:
   db.rollback()
db.close()

删除数据

table = 'demo'
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 * 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')

fetch()存在指针偏移的问题,使用一次,指针就会向后偏移一次。

posted @ 2017-10-09 20:15  cnkai  阅读(394)  评论(0编辑  收藏  举报