python Sqlite3相关基本操作

Posted lzhida

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Sqlite3相关基本操作相关的知识,希望对你有一定的参考价值。

1、连接数据库

1 import sqlite3
2 
3 conn = sqlite3.connect(test.db)

2、创建表

 1 import sqlite3
 2 
 3 conn = sqlite3.connect(test.db)
 4 print "Opened database successfully";
 5 c = conn.cursor()
 6 c.execute(‘‘‘CREATE TABLE COMPANY
 7        (ID INT PRIMARY KEY     NOT NULL,
 8        NAME           TEXT    NOT NULL,
 9        AGE            INT     NOT NULL,
10        ADDRESS        CHAR(50),
11        SALARY         REAL);‘‘‘)
12 print "Table created successfully";
13 conn.commit()
14 conn.close()

3、INSERT 操作

 1 import sqlite3
 2 
 3 conn = sqlite3.connect(test.db)
 4 c = conn.cursor()
 5 print "Opened database successfully";
 6 
 7 c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)  8       VALUES (1, ‘Paul‘, 32, ‘California‘, 20000.00 )");
 9 
10 c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) 11       VALUES (2, ‘Allen‘, 25, ‘Texas‘, 15000.00 )");
12 
13 c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) 14       VALUES (3, ‘Teddy‘, 23, ‘Norway‘, 20000.00 )");
15 
16 c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) 17       VALUES (4, ‘Mark‘, 25, ‘Rich-Mond ‘, 65000.00 )");
18 
19 conn.commit()
20 print "Records created successfully";
21 conn.close()

4、SELECT 操作

 1 import sqlite3
 2 
 3 conn = sqlite3.connect(test.db)
 4 c = conn.cursor()
 5 print "Opened database successfully";
 6 
 7 cursor = c.execute("SELECT id, name, address, salary  from COMPANY")
 8 for row in cursor:
 9    print "ID = ", row[0]
10    print "NAME = ", row[1]
11    print "ADDRESS = ", row[2]
12    print "SALARY = ", row[3], "
"
13 
14 print "Operation done successfully";
15 conn.close()

5、UPDATE 操作

 1 import sqlite3
 2 
 3 conn = sqlite3.connect(test.db)
 4 c = conn.cursor()
 5 print "Opened database successfully";
 6 
 7 c.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")
 8 conn.commit()
 9 print "Total number of rows updated :", conn.total_changes
10 
11 cursor = conn.execute("SELECT id, name, address, salary  from COMPANY")
12 for row in cursor:
13    print "ID = ", row[0]
14    print "NAME = ", row[1]
15    print "ADDRESS = ", row[2]
16    print "SALARY = ", row[3], "
"
17 
18 print "Operation done successfully";
19 conn.close()

6、DELETE 操作

import sqlite3

conn = sqlite3.connect(test.db)
c = conn.cursor()
print "Opened database successfully";

c.execute("DELETE from COMPANY where ID=2;")
conn.commit()
print "Total number of rows deleted :", conn.total_changes

cursor = conn.execute("SELECT id, name, address, salary  from COMPANY")
for row in cursor:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "
"

print "Operation done successfully";
conn.close()

7、执行sql语句时的格式

执行SQL语句。 可以是参数化 SQL 语句(即,在 SQL 语句中使用占位符)。sqlite3 模块支持两种占位符:问号(qmark风格)和命名占位符(命名风格)。

示例如下:

 1 import sqlite3
 2 
 3 con = sqlite3.connect(":memory:")
 4 cur = con.cursor()
 5 cur.execute("create table people (name_last, age)")
 6 
 7 who = "Yeltsin"
 8 age = 72
 9 
10 # This is the qmark style:
11 cur.execute("insert into people values (?, ?)", (who, age))
12 
13 # And this is the named style:
14 cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
15 
16 print(cur.fetchone())
17 
18 con.close()

8、外键使用

1. sqlite3 默认为关闭外键限制的,如要打开,请执行如下命令:

 1 PRAGMA FOREIGN_KEYS=ON; 

2、外键创建:

 1 create table parent_t
 2 
 3 (
 4 parent_id INTEGER NOT NULL PRIMARY KEY,
 5 parent_name TEXT
 6 );
 7 
 8 create table child_t
 9 (
10 child_t INTEGER NOT NULL PRIMARY KEY,
11 child_name TEXT NOT NULL,
12 parent_id INTEGER NOT NULL,
13 FOREIGN KEY (parent_id) REFERENCES parent_t(parent_id) ON DELETE CASCADE ON UPDATE CASCADE
14 );

 

3、另一种创建方式:

 1 create table parent_t
 2 
 3 (
 4 parent_id INTEGER NOT NULL PRIMARY KEY,
 5 parent_name TEXT
 6 );
 7 
 8 create table child_t
 9 (
10 child_t INTEGER NOT NULL PRIMARY KEY,
11 child_name TEXT NOT NULL,
12 parent_id INTEGER NOT NULL,
13 parent_id INTEGER REFERENCES parent_t(parent_id) ON DELETE CASCADE ON UPDATE CASCADE
14 );

 

9、其他sql语句

1.SqLite判断表是否存在,如果存在则删除该表:

技术图片
1 DROP TABLE IF EXISTS TableName
View Code

2.SqLite判断表是否存在,如果不存在则创建指定的表:

1 CREATE TABLE IF NOT EXISTS TableName( 
2     Id          INTEGER         PRIMARY KEY AUTOINCREMENT,
3     Url         VARCHAR( 150 ),
4     IsCrawled   BOOLEAN         NOT NULL,
5     CreatedOn   DATETIME        NOT NULL,
6     CrawledDate DATETIME 
7 );

 

以上是关于python Sqlite3相关基本操作的主要内容,如果未能解决你的问题,请参考以下文章

Python内置数据结构操作VS sqlite3操作

在 SQLite3 DELETE 语句中引用 python 变量

Python编程之sqlite3数据库

在 SQLite3 表中的行上有效地执行 python 代码

python3.5中import sqlite3报错:ImportError: No module named _sqlite3

Android 逆向使用 DB Browser 查看并修改 SQLite 数据库 ( 从 Android 应用数据目录中拷贝数据库文件 | 使用 DB Browser 工具查看数据块文件 )(代码片段