Python数据库

来源:互联网 发布:淘宝上买cf王者靠谱吗 编辑:程序博客网 时间:2024/05/16 01:58
Python数据库
使用dbm持久字典
很多情况下并不需要一个成熟的关系数据库,此时使用dbm文件创建一个持久字典即可.
使用持久字典存储名称/值对,键和值都必须是字符串类型。
* 创建持久字典eg:
import dbm
db = dbm.open('websites','c')
db['www.python.org'] = 'Python home page'
print(db['www.python.org'])
db.close()
输出:
b'Python home page'
标志:c —— 打开文件,必要时创建
    N —— 打开(创建),若存在,覆盖
    W —— 打开文件,若存在,不会创建
如果希望保存一个对象,可以使用pickle(泡菜?)模块对它就行串行化。
* 访问持久字典eg:
import dbm
db = dbm.open('websites','w')
db['www.wrox.com'] = 'Wrox home page'
if db['www.python.org'] != None:
    print('Found www.python.org')
else:
    print('Error: Missing item')
for key in db.keys():
    print("key = ", key, " value = ", db[key])
del db['www.wrox.com']
print("After deleting www.wrox.com,we have: ")
for key in db.keys():
    print("key = ", key, " value = ",db[key])
db.close()
输出:
Found www.python.org
key =  b'www.python.org'  value =  b'Python home page'
key =  b'www.wrox.com'  value =  b'Wrox home page'
After deleting www.wrox.com,we have:
key =  b'www.python.org'  value =  b'Python home page'
#close方法关闭了字典,将对字典的所有修改保存到硬盘上
##########################################################################################
使用dbm还是关系数据库?
* 若数据需求很简单,可用键/值对,使用dbm持久字典
* 若计划之存储少量数据,使用dbm
* 若需要支持事务(控制并发),使用关系数据库
* 若需要一些复杂的数据结构或多个连接数据的表,数据库
* 若需要与一个已有的系统协作,此系统极大可能是数据库,so...
##########################################################################################
使用Sqlite数据库
创建一个SQLite3数据库:
import os
import sqlite3
conn = sqlite3.connect('sqlite_test/sample_database')
cursor = conn.cursor()
cursor.execute("""
    create table employee(
    empid integer,
    firstname varchar,
    lastname varchar,
    dept integer,
    manager integer,
    phone varchar)
    """)
cursor.execute("""
    create table department(
    departmentid integer,
    name varchar,
    manager integer)
    """)
cursor.execute("""
    create table user(
    userid integer,
    username varchar,
    employeeid integer)
    """)
cursor.execute("""create index userid on user (userid)""")
cursor.execute("""create index impid on employee (empid)""")
cursor.execute("""create index deptid on department (departmentid)""")
cursor.execute("""create index deptfk on employee (dept)""")
cursor.execute("""create index mgr on employee (manager)""")
cursor.execute("""create index emplid on user (employeeid)""")
cursor.execute("""create index deptmgr on department (manager)""")
conn.commit()  #将所有修改保存到磁盘上
cursor.close()
conn.close()
没有任何输出
##########################################################################################
使用Python的通用DB API:
一个DB_API兼容的模块必须定义如下所有的全局属性:
*****************************************
apilevel    DB-API 模块兼容的DB-API最高版本
threadsafety    线程安全级别
paramstyle    该模块支持的SQL语句参数风格
connect()   连接函数
***************
threadsafety:
    0:  不支持线程安全,多个线程不能共享此模块
    1: 线程可以共享模块,但不能共享连接
    2: 线程可以共享模块和连接,但不能共享游标
    3: 线程可以共享模块,连接及游标
如果资源被共享,必须使用自旋锁或信号量这样的同步原语对其进行原子目标锁定。
##########################################################################################
import MySQLdb
#以root身份登录,赋予普通用户相应权限
cxn = MySQLdb.connect(user = 'root')
cxn.query('DROP DATABASE test')
#若数据库不存在:
cxn.query('CREATE DATABASE test')
cxn.query("GRANT ALL ON test.* to ''@'localhost'")
cxn.commit()
cxn.close()
#之后以普通用户再次连接,建表,查询
cxn = MySQLdb.connect(db = 'test')
cur = cxn.cursor()
cur.execute('CREATE TABLE users(login VARCHAR(8),uid INT)')
#插入数据,读取数据
cur.execute("INSERT INTO users VALUES('john',7000"))
cur.execute("INSERT INTO users VALUES('jane',7001)")
cur.execute("INSERT INTO users VALUES('bob',7200)")
cur.execute("SELECT * FROM users WHERE login LIKE 'j%'")
for data in cur.fetchall():
    print ('%s\t%s' %data)
#更新和删除
cur.execute("UPDATE users SET uid = 7100 WHERE uid = 7001")
cur.execute("SELECT * FROM users")
for data in cur.fetchall():
    print('%s\t%s' %data)
cur.execute('DELETE FROM users WHERE login = "bob"')
cur.execute('DROP TABLE users')
cur.close()
cxn.commit()
cxn.close()
##########################################################################################
                                             
0 0
原创粉丝点击