Python 需要检查和填充sqlite数据库管理和操作代码吗
全部, 更新:根据谷歌搜索结果和答案,我添加了更多提示,但仍未完成。Python 需要检查和填充sqlite数据库管理和操作代码吗,python,database,sqlite,sqlalchemy,Python,Database,Sqlite,Sqlalchemy,全部, 更新:根据谷歌搜索结果和答案,我添加了更多提示,但仍未完成。 import sqlite3 import os database_name = "newdb.db" if not os.path.isfile(database_name): print "the database already exist" # connect to to db, refer #2 db_connection = sqlite3.connect(database_name) db_
import sqlite3
import os
database_name = "newdb.db"
if not os.path.isfile(database_name):
print "the database already exist"
# connect to to db, refer #2
db_connection = sqlite3.connect(database_name)
db_cursor = db_connection.cursor()
在使用sqlite3和学习sqlalchemy的过程中,我发现为了管理数据,有必要编写下面的代码,然而,在sqlalchemy中这样做对我来说可能是一个困难的部分,然后我回到sqlite3模块
下面的代码列出了10个以上的步骤作为家务工作,其中大部分来自网络,我怀疑有专业知识的人是否能够检查并填充缺少的部分。
如果有人知道如何在SQLAlchemy中做到这一点,你也能分享一下吗
1。测试数据库文件是否存在
import sqlite3
import os
database_name = "newdb.db"
if not os.path.isfile(database_name):
print "the database already exist"
# connect to to db, refer #2
db_connection = sqlite3.connect(database_name)
db_cursor = db_connection.cursor()
2。测试数据库文件是否为有效的sqlite3格式
http://stackoverflow.com/questions/1516508/sqlite3-in-python
>>> c.execute("SELECT * FROM tbl")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.DatabaseError: file is encrypted or is not a database
=========sqlalchemy way ===============
http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg20860.html
import os, os.path as osp
try:
from pysqlite2 import dbapi2 as sqlite
except:
import sqlite3 as sqlite
def isSQLite(filename):
"""True if filename is a SQLite database
File is database if: (1) file exists, (2) length is non-zero,
(3) can connect, (4) has sqlite_master table
"""
# validate file exists
if not osp.isfile(filename):
return False
# is not an empty file
if not os.stat(filename).st_size:
return False
# can open a connection
try:
conn = sqlite.connect(filename)
except:
return False
# has sqlite_master
try:
result = conn.execute('pragma table_info(sqlite_master)').fetchall()
if len(result) == 0:
conn.close()
return False
except:
conn.close()
return False
# looks like a good database
conn.close()
return True
c=conn.cursor()
if table_name in [row for row in c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';")]
4.备份磁盘中的数据库文件
http://stuvel.eu/archive/55/safely-copy-a-sqlite-database
import shutil, os, sqlite3
if not os.path.isdir ( backupdir ):
raise Exception
backupfile = os.path.join ( backupdir, os.path.basename(dbfile) + time.strftime(".%Y%m%d-%H%M") )
db = sqlite3.connect ( dbfile )
cur = db.cursor ()
cur.execute ( 'begin immediate' )
shutil.copyfile ( dbfile, backupfile )
cur.execute ( 'rollback' )
=========or========
http://github.com/husio/python-sqlite3-backup
=========or========
http://docs.python.org/release/2.6/library/sqlite3.html#sqlite3.Connection.iterdump
c = sqlite.connect(database_name, timeout=30.0) # default 5sec
5。备份表-在同一数据库文件中
c=conn.cursor()
c.execute("CREATE TABLE demo_backup AS SELECT * FROM demo;")
c.execute("ALTER TABLE foo RENAME TO bar;")
6。重命名表格
c=conn.cursor()
c.execute("CREATE TABLE demo_backup AS SELECT * FROM demo;")
c.execute("ALTER TABLE foo RENAME TO bar;")
7。将表复制到不同的数据库或从不同的数据库复制表:
Thanks, MPelletier
Connect to one database
db_connection = sqlite3.connect(database_file)
Attach the second database
db_connection.execute("ATTACH database_file2 AS database_name2")
Insert from one to the other:
db_connection.execute("INSERT INTO FooTable SELECT * FROM database_name2.FooTable")
==========or============
db_connection.execute("INSERT INTO database_name2.FooTable SELECT * FROM FooTable")
========sqlalchemy way======
http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg11563.html
def duplicateToDisk(self, file):
'''Tohle ulozi databazi, ktera byla pouze v pameti, na disk'''
cur = self.connection()
import os
if os.path.exists(file):
os.remove(file)
cur.execute("attach %s as extern" % file)
self.checkTable('extern.dictionary')
cur.execute("insert into extern.dictionary select * from dictionary")
cur.execute("detach extern")
self.commit()
http://code.activestate.com/recipes/526618/
http://www.yeraze.com/2009/01/python-sqlite-multiple-threads/
8测试数据库是否已锁定?
#possible?
try:
c = sqlite.connect(database_name, timeout=0)
c.commit()
except OperationalError # OperationalError: database is locked
refer #12
#from FAQ
#try to reuse the connection pool from SQLAlchemy
engine = create_engine(...)
conn = engine.connect() #****1
conn.connection.<do DBAPI things>
cursor = conn.connection.cursor(<DBAPI specific arguments..>)
===or ==== can out of pool's manage
conn = engine.connect()
conn.detach() # detaches the DBAPI connection from the connection pool
conn.connection.<go nuts>
conn.close() # connection is closed for real, the pool replaces it with a new connect
========and not sure if this works ===========
#from sqlalchemy document #http://www.sqlalchemy.org/docs/reference/sqlalchemy/pooling.html?highlight=connection%20pool
import sqlalchemy.pool as pool
import sqlite3 as sqlite3
conn_proxy = pool.manage(sqlite3)
# then connect normally
connection = conn_proxy.connect(...)
=====================================================================
#****1 : what is #****1 on above code invoked =_=!!
A engine.raw_connection()
=
A pool.unique_connection()
=
A _ConnectionFairy(self).checkout()
=
A return _ConnectionFairy <== cls
= _connection_record.get_connection()
= _ConnectionRecord.connection
= return a pool.creator **which is a callable function that returns a DB-API connection object**
9。连接到数据库超时,等待其他调用程序释放锁
http://stuvel.eu/archive/55/safely-copy-a-sqlite-database
import shutil, os, sqlite3
if not os.path.isdir ( backupdir ):
raise Exception
backupfile = os.path.join ( backupdir, os.path.basename(dbfile) + time.strftime(".%Y%m%d-%H%M") )
db = sqlite3.connect ( dbfile )
cur = db.cursor ()
cur.execute ( 'begin immediate' )
shutil.copyfile ( dbfile, backupfile )
cur.execute ( 'rollback' )
=========or========
http://github.com/husio/python-sqlite3-backup
=========or========
http://docs.python.org/release/2.6/library/sqlite3.html#sqlite3.Connection.iterdump
c = sqlite.connect(database_name, timeout=30.0) # default 5sec
10强制所有数据库连接释放/提交A.K.A以释放所有锁?
#possible?
try:
c = sqlite.connect(database_name, timeout=0)
c.commit()
except OperationalError # OperationalError: database is locked
refer #12
#from FAQ
#try to reuse the connection pool from SQLAlchemy
engine = create_engine(...)
conn = engine.connect() #****1
conn.connection.<do DBAPI things>
cursor = conn.connection.cursor(<DBAPI specific arguments..>)
===or ==== can out of pool's manage
conn = engine.connect()
conn.detach() # detaches the DBAPI connection from the connection pool
conn.connection.<go nuts>
conn.close() # connection is closed for real, the pool replaces it with a new connect
========and not sure if this works ===========
#from sqlalchemy document #http://www.sqlalchemy.org/docs/reference/sqlalchemy/pooling.html?highlight=connection%20pool
import sqlalchemy.pool as pool
import sqlite3 as sqlite3
conn_proxy = pool.manage(sqlite3)
# then connect normally
connection = conn_proxy.connect(...)
=====================================================================
#****1 : what is #****1 on above code invoked =_=!!
A engine.raw_connection()
=
A pool.unique_connection()
=
A _ConnectionFairy(self).checkout()
=
A return _ConnectionFairy <== cls
= _connection_record.get_connection()
= _ConnectionRecord.connection
= return a pool.creator **which is a callable function that returns a DB-API connection object**
11。在python中使用sqlite时使用多线程:
Thanks, MPelletier
Connect to one database
db_connection = sqlite3.connect(database_file)
Attach the second database
db_connection.execute("ATTACH database_file2 AS database_name2")
Insert from one to the other:
db_connection.execute("INSERT INTO FooTable SELECT * FROM database_name2.FooTable")
==========or============
db_connection.execute("INSERT INTO database_name2.FooTable SELECT * FROM FooTable")
========sqlalchemy way======
http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg11563.html
def duplicateToDisk(self, file):
'''Tohle ulozi databazi, ktera byla pouze v pameti, na disk'''
cur = self.connection()
import os
if os.path.exists(file):
os.remove(file)
cur.execute("attach %s as extern" % file)
self.checkTable('extern.dictionary')
cur.execute("insert into extern.dictionary select * from dictionary")
cur.execute("detach extern")
self.commit()
http://code.activestate.com/recipes/526618/
http://www.yeraze.com/2009/01/python-sqlite-multiple-threads/
12从SQLAlchemy获取连接?
#possible?
try:
c = sqlite.connect(database_name, timeout=0)
c.commit()
except OperationalError # OperationalError: database is locked
refer #12
#from FAQ
#try to reuse the connection pool from SQLAlchemy
engine = create_engine(...)
conn = engine.connect() #****1
conn.connection.<do DBAPI things>
cursor = conn.connection.cursor(<DBAPI specific arguments..>)
===or ==== can out of pool's manage
conn = engine.connect()
conn.detach() # detaches the DBAPI connection from the connection pool
conn.connection.<go nuts>
conn.close() # connection is closed for real, the pool replaces it with a new connect
========and not sure if this works ===========
#from sqlalchemy document #http://www.sqlalchemy.org/docs/reference/sqlalchemy/pooling.html?highlight=connection%20pool
import sqlalchemy.pool as pool
import sqlite3 as sqlite3
conn_proxy = pool.manage(sqlite3)
# then connect normally
connection = conn_proxy.connect(...)
=====================================================================
#****1 : what is #****1 on above code invoked =_=!!
A engine.raw_connection()
=
A pool.unique_connection()
=
A _ConnectionFairy(self).checkout()
=
A return _ConnectionFairy <== cls
= _connection_record.get_connection()
= _ConnectionRecord.connection
= return a pool.creator **which is a callable function that returns a DB-API connection object**
#来自常见问题解答
#尝试重用SQLAlchemy中的连接池
引擎=创建引擎(…)
conn=发动机连接()#**1
连接。
cursor=conn.connection.cursor()
===或===无法从池中管理
conn=引擎连接()
conn.detach()#从连接池中分离DBAPI连接
连接。
conn.close()#实际连接已关闭,池将用新连接替换它
=========不确定这是否有效===========
#来自sqlalchemy文档#http://www.sqlalchemy.org/docs/reference/sqlalchemy/pooling.html?highlight=connection%20pool
将sqlalchemy.pool导入为池
将sqlite3导入为sqlite3
conn_proxy=pool.manage(sqlite3)
#然后正常连接
connection=conn\u proxy.connect(…)
=====================================================================
#****1:上面调用的代码上的#**1是什么=#=!!
引擎。原始连接()
=
一个池。唯一的_连接()
=
A_ConnectionFairy(self.checkout)()
=
返回_ConnectionFairy要将数据复制到不同的数据库或从不同的数据库复制数据,一般的SQLite方法是:
连接到一个数据库
db_connection = sqlite3.connect(database_file)
附加第二个数据库
db_connection.execute("ATTACH database_file2 AS database_name2")
从一个插入到另一个:
db_connection.execute("INSERT INTO FooTable SELECT * FROM database_name2.FooTable")
或
显然,您不希望定期执行步骤5和步骤6,我认为#8不起作用(仅通过提交即可锁定测试数据库)。我的数据库包装器在每个事务上提交,即使只是选择,但如果我执行写入(插入、更新或删除),我只会得到数据库被锁定错误。相反,我只是通过更改虚拟表中的值来测试它。