python-Sqlite3 常用方法

创建/连接数据库

conn = sqlite3.connect('C:/Patent/patent.db')
conn.execute("PRAGMA synchronous = OFF;") 
conn.execute("PRAGMA cache_size = 40000;")
conn.execute("PRAGMA journal_mode = memory;")

遍历数据库中的表

command = "select name from sqlite_master where type='table' order by name;"
cursor = conn.execute(command)
res = cursor.fetchall()
print("DB has %d tables, names are :" %len(res))
for table in res:
    print("%s",%table[0])

创建表

  • 表名称不含变量
 conn.execute('''CREATE TABLE STAFF
                    (
                     NAME               TEXT  NOT NULL,
                     AGE                TEXT,
                     TITLE              TEXT);
                ''')
  • 表名称含变量(动态创建)
DBTable = "TABLE" + str(count)
sqlStr = "CREATE TABLE if not exists " + DBTable + " (ID TEXT, DATE TEXT);"
conn.execute(sqlStr)
conn.commit()

向表中写入数据

DBTable = "TABLE" + str(count)
value = (Array1[j][k], str(Array2[j][k]))
ins = "INSERT OR IGNORE INTO " + DBTable + " (ID, DATE) VALUES (?,?);"
conn.execute(ins, value)
conn.commit() 

查询数据项

#查询该公司相关的所有专利
fuzzyName = "%"+Name+"%"
Age = '30'
command = "SELECT *  from TABLE WHERE NAME like '%s' AND AGE like '%s'" %(fuzzyName, Age)
cursor = conn.execute(command)
res = cursor.fetchall()
total = len(res)
if(total)
    #分析每一项数据信息
    for one in res:
        #do something here

更新数据项

value = (newAge, name)
ins = "update TABLE set AGE = ? where NAME = ?;" 
conn.execute(ins, value)
conn.commit()  

关闭数据库

conn.close()

注意事项

  • Sqlite关键字不可用于表名、列名;
  • 表名不可以数字开头;
  • 另附Sqlite官方给出的关键字:
ABORT
ACTION
ADD
AFTER
ALL
ALTER
ANALYZE
AND
AS
ASC
ATTACH
AUTOINCREMENT
BEFORE
BEGIN
BETWEEN
BY
CASCADE
CASE
CAST
CHECK
COLLATE
COLUMN
COMMIT
CONFLICT
CONSTRAINT  CREATE
CROSS
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
DATABASE
DEFAULT
DEFERRABLE
DEFERRED
DELETE
DESC
DETACH
DISTINCT
DROP
EACH
ELSE
END
ESCAPE
EXCEPT
EXCLUSIVE
EXISTS
EXPLAIN
FAIL
FOR
FOREIGN FROM
FULL
GLOB
GROUP
HAVING
IF
IGNORE
IMMEDIATE
IN
INDEX
INDEXED
INITIALLY
INNER
INSERT
INSTEAD
INTERSECT
INTO
IS
ISNULL
JOIN
KEY
LEFT
LIKE
LIMIT
MATCH   NATURAL
NO
NOT
NOTNULL
NULL
OF
OFFSET
ON
OR
ORDER
OUTER
PLAN
PRAGMA
PRIMARY
QUERY
RAISE
RECURSIVE
REFERENCES
REGEXP
REINDEX
RELEASE
RENAME
REPLACE
RESTRICT
RIGHT   ROLLBACK
ROW
SAVEPOINT
SELECT
SET
TABLE
TEMP
TEMPORARY
THEN
TO
TRANSACTION
TRIGGER
UNION
UNIQUE
UPDATE
USING
VACUUM
VALUES
VIEW
VIRTUAL
WHEN
WHERE
WITH
WITHOU

你可能感兴趣的:(Python)