假设这样一种情况,当在同一时间有多个数据库可用,您想使用其中的任何一个。SQLite 的 ATTACH DATABASE 语句是用来选择一个特定的数据库,使用该命令后,所有的 SQLite 语句将在附加的数据库下执行。
SQLite 的 ATTACH DATABASE 语句的基本语法如下:
1 |
<span class="pln">ATTACH DATABASE </span><span class="str">'DatabaseName'</span> <span class="typ">As</span> <span class="str">'Alias-Name'</span><span class="pun">;</span> |
如果数据库尚未被创建,上面的命令将创建一个数据库,如果数据库已存在,则把数据库文件名称与逻辑数据库 'Alias-Name' 绑定在一起。
如果想附加一个现有的数据库 testDB.db,则 ATTACH DATABASE 语句将如下所示:
1 |
<span class="pln">sqlite</span><span class="pun">></span><span class="pln"> ATTACH DATABASE </span><span class="str">'testDB.db'</span> <span class="kwd">as</span> <span class="str">'TEST'</span><span class="pun">;</span> |
使用 SQLite .database 命令来显示附加的数据库。
1 2 3 4 5 |
<span class="pln">sqlite</span><span class="pun">></span> <span class="pun">.</span><span class="pln">database seq name file </span><span class="pun">---</span> <span class="pun">---------------</span> <span class="pun">----------------------</span> <span class="lit">0</span><span class="pln"> main </span><span class="pun">/</span><span class="pln">home</span><span class="pun">/</span><span class="pln">sqlite</span><span class="pun">/</span><span class="pln">testDB</span><span class="pun">.</span><span class="pln">db </span><span class="lit">2</span><span class="pln"> test </span><span class="pun">/</span><span class="pln">home</span><span class="pun">/</span><span class="pln">sqlite</span><span class="pun">/</span><span class="pln">testDB</span><span class="pun">.</span><span class="pln">db</span> |
数据库名称 main 和 temp 被保留用于主数据库和存储临时表及其他临时数据对象的数据库。这两个数据库名称可用于每个数据库连接,且不应该被用于附加,否则将得到一个警告消息,如下所示:
1 2 3 4 5 6 7 |
<span class="pln">sqlite</span><span class="pun">></span><span class="pln"> ATTACH DATABASE </span><span class="str">'testDB.db'</span> <span class="kwd">as</span> <span class="str">'TEMP'</span><span class="pun">;</span> <span class="typ">Error</span><span class="pun">:</span><span class="pln"> database TEMP </span><span class="kwd">is</span><span class="pln"> already </span><span class="kwd">in</span> <span class="kwd">use</span><span class="pln"> sqlite</span><span class="pun">></span><span class="pln"> ATTACH DATABASE </span><span class="str">'testDB.db'</span> <span class="kwd">as</span> <span class="str">'main'</span><span class="pun">;</span> <span class="typ">Error</span><span class="pun">:</span><span class="pln"> database TEMP </span><span class="kwd">is</span><span class="pln"> already </span><span class="kwd">in</span> <span class="kwd">use from:<a href="http://www.runoob.com/sqlite/sqlite-attach-database.html">http://www.runoob.com/sqlite/sqlite-attach-database.html</a></span> |