Python——操作数据库(二)

Demo-01

  1 import pymysql
  2 #连接数据库
  3 db = pymysql.connect(host='localhost',user='root', password='123456', port=3306)
  4 #获取游标
  5 cursor = db.cursor()
  6 #执行
  7 cursor.execute('SELECT VERSION()')
  8 #fetchone()获取结果集下一行
  9 data = cursor.fetchone()
 10 #输出
 11 print('Database version:', data)
 12 #执行
 13 cursor.execute("CREATE DATABASE spiders DEFAULT CHARACTER SET utf8")
 14 db.close()

Demo-02

  1 import pymysql
  2 
  3 #连接数据库
  4 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
  5 #获取游标
  6 cursor = db.cursor()
  7 #sql语句
  8 sql = 'CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id))'
  9 #执行sql语句
 10 cursor.execute(sql)
 11 #关闭数据库
 12 db.close()

Demo-03

  1 import pymysql
  2 
  3 id = '20120001'
  4 user = 'Bob'
  5 age = 20
  6 
  7 #连接数据库
  8 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
  9 #获取游标
 10 cursor = db.cursor()
 11 #sql语句
 12 sql = 'INSERT INTO students(id, name, age) values(%s, %s, %s)'
 13 try:
 14 	#执行语句
 15     cursor.execute(sql, (id, user, age))
 16 	#提交到数据库执行
 17     db.commit()
 18 except:
 19 	#如果发生错误则回滚
 20     db.rollback()
 21 #关闭资源
 22 db.close()

Demo-04

  1 import pymysql
  2 
  3 data = {
  4     'id': '20120001',
  5     'name': 'Bob',
  6     'age': 20
  7 }
  8 #表
  9 table = 'students'
 10 keys = ', '.join(data.keys())
 11 values = ', '.join(['%s'] * len(data))
 12 #sql语句
 13 sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
 14 #连接数据库
 15 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
 16 #获取游标
 17 cursor = db.cursor()
 18 try:
 19     if cursor.execute(sql, tuple(data.values())):
 20         print('Successful')
 21 		#提交到数据库执行
 22         db.commit()
 23 except:
 24     print('Failed')
 25 	#发生错误则回滚
 26     db.rollback()
 27 #关闭资源
 28 db.close()

Demo-05

  1 import pymysql
  2 
  3 data = {
  4     'id': '20120001',
  5     'name': 'Bob',
  6     'age': 20
  7 }
  8 table = 'students'
  9 keys = ', '.join(data.keys())
 10 values = ', '.join(['%s'] * len(data))
 11 
 12 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
 13 cursor = db.cursor()
 14 
 15 sql = 'UPDATE students SET age = %s WHERE name = %s'
 16 try:
 17     cursor.execute(sql, (25, 'Bob'))
 18     db.commit()
 19 except:
 20     db.rollback()
 21 db.close()
 22 
 23 

Demo-06

  1 import pymysql
  2 
  3 data = {
  4     'id': '20120001',
  5     'name': 'Bob',
  6     'age': 21
  7 }
  8 
  9 table = 'students'
 10 keys = ', '.join(data.keys())
 11 values = ', '.join(['%s'] * len(data))
 12 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
 13 cursor = db.cursor()
 14 sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table, keys=keys,
 15                                                                                      values=values)
 16 update = ','.join([" {key} = %s".format(key=key) for key in data])
 17 sql += update
 18 try:
 19     if cursor.execute(sql, tuple(data.values()) * 2):
 20         print('Successful')
 21         db.commit()
 22 except:
 23     print('Failed')
 24     db.rollback()
 25 db.close()

Demo-07

  1 import pymysql
  2 
  3 table = 'students'
  4 condition = 'age > 20'
  5 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
  6 cursor = db.cursor()
  7 sql = 'DELETE FROM  {table} WHERE {condition}'.format(table=table, condition=condition)
  8 try:
  9     cursor.execute(sql)
 10     db.commit()
 11 except:
 12     db.rollback()
 13 
 14 db.close()

Demo-08

  1 import pymysql
  2 
  3 sql = 'SELECT * FROM students WHERE age >= 20'
  4 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
  5 cursor = db.cursor()
  6 try:
  7     cursor.execute(sql)
  8     print('Count:', cursor.rowcount)
  9     row = cursor.fetchone()
 10     while row:
 11         print('Row:', row)
 12         row = cursor.fetchone()
 13 except:
 14     print('Error')


你可能感兴趣的:(Python——操作数据库(二))