SQLite
# -*- coding: utf-8 -*-
# 导入SQLite驱动:
import sqlite3
# 连接到SQLite数据库
# 数据库文件是test.db
# 如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect('test.db')
# 创建一个Cursor:
cursor = conn.cursor()
# 执行一条SQL语句,创建user表:
# cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# <sqlite3.Cursor object at 0x10f8aa260>
# 继续执行一条SQL语句,插入一条记录:
cursor.execute('insert into user (id, name) values (\'4\', \'Michael\')')
# <sqlite3.Cursor object at 0x10f8aa260>
# 通过rowcount获得插入的行数:
print cursor.rowcount
# 关闭Cursor:
cursor.close()
# 提交事务:
conn.commit()
# 关闭Connection:
conn.close()
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
# 执行查询语句:
cursor.execute('select * from user where id=?', '3')
# <sqlite3.Cursor object at 0x10f8aa340>
# 获得查询结果集:
values = cursor.fetchall()
print values
# [(u'1', u'Michael')]
cursor.close()
conn.close()
MySQL
# -*- coding: utf-8 -*-
# 导入MySQL驱动
import mysql.connector
# MySQL的SQL占位符是%s;
# 通常我们在连接MySQL时传入use_unicode=True,
# 让MySQL的DB-API始终返回Unicode。
# 注意把password设为你的root口令:
conn = mysql.connector.connect(user='root', password='password', database='test', use_unicode=True)
cursor = conn.cursor()
# 创建user表:
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意MySQL的占位符是%s:
cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
cursor.rowcount
# 提交事务:
conn.commit()
cursor.close()
# 运行查询:
cursor = conn.cursor()
cursor.execute('select * from user where id = %s', '1')
values = cursor.fetchall()
print values
# 关闭Cursor和Connection:
cursor.close()
conn.close()