参考廖雪峰的Python教程,实现Python3 SQLite、MySQL数据库编程
SQLite
#!/usr/bin/python3
# coding: utf-8
db_name = "test.db"
db_existed = False
import os
import sqlite3
for root, dirs, files in os.walk("."):
if db_name in files:
db_existed = True
conn = sqlite3.connect("test.db")
cursor = conn.cursor()
if not db_existed:
cursor.execute('''
create table user (
id varchar(20) primary key,
name varchar(20))
''')
for i in range(1, 10):
cursor.execute("insert into user values(\"%s\", \"python%s\")" %(i, i))
conn.commit()
cursor.execute("select id, name from user")
values = cursor.fetchall()
for value in values:
print(value[0], value[1])
cursor.execute("select id, name from user where id = ?", ("3"))
values = cursor.fetchall()
for value in values:
print(value[0], value[1])
cursor.execute("select id, name from user where id = ? or name = ?", ("3", "python3"))
values = cursor.fetchall()
for value in values:
print(value[0], value[1])
cursor.close()
conn.close()
MySQL
#!/usr/bin/python3
# coding: utf-8
import mysql.connector
conn = mysql.connector.connect(user="xxx", password="xxx", database="python")
cursor = conn.cursor()
cursor.execute("drop table if exists user;")
cursor.execute("create table user(id varchar(20) primary key, name varchar(20));")
conn.commit()
for i in range(1, 10):
cursor.execute("insert into user values(%s, %s);", ["%s" %(i), "python%s" %(i)])
conn.commit()
cursor.close()
cursor = conn.cursor()
cursor.execute("select id, name from user;")
values = cursor.fetchall()
for value in values:
print(value[0], value[1])
cursor.execute("select id, name from user where id = %s or name = %s;", [3, "python3"])
values = cursor.fetchall()
for value in values:
print(value[0], value[1])
cursor.close()
conn.close()