Python 初步试用sqlite

简述:

在eclipse里装了python3.2的插件,做一些对SQLite的操作。

(参考官方网址http://docs.python.org/library/sqlite3.html#module-sqlite3)


过程A :

1. 新建一个python项目文件test

2. 输入新建一个数据库example.db

import sqlite3
conn = sqlite3.connect('example.db')

run一下,这时就会新增test/example.db文件

Python 初步试用sqlite_第1张图片


3. 实现table的建立

sql = '''
--- Drop tables in reversed order
drop table if exists animals;

CREATE TABLE animals(  --- 'animals' 
    animal_id          integer primary key,
    name            varchar(32) not null,
    age             integer not null      
);
''';
cur.executescript(sql); #use excutescript function exec several sql statements

4. 插入一行数据

sql_A = "INSERT INTO animals (dog_id,name,age) VALUES (0,'dogA',1)"
cur.execute(sql_A) #ececute function exec only one statement

5. select 刚才insert的数据,python自动存放在一个list里,做一个输出:

nameA = "dogA";
output = cur.execute("SELECT * FROM animals WHERE name = '%s'" % nameA);
for row in output:
    print (row);

过程1代码:

import sqlite3

conn = sqlite3.connect('example.db');
cur = conn.cursor();


'''Table Creation Operation'''
sql = '''
--- Drop tables in reversed order
drop table if exists animals;

CREATE TABLE animals(  --- 'animals' 
    animal_id          integer primary key,
    name            varchar(32) not null,
    age             integer not null      
);
''';
cur.executescript(sql); #use excutescript function exec several sql statements

'''Insert Operation'''
sql_A = "INSERT INTO animals (animal_id,name,age) VALUES (0,'dogA',1)"
cur.execute(sql_A) #ececute function exec only one statement

'''select Operation'''
nameA = "dogA";
output = cur.execute("SELECT * FROM animals WHERE name = '%s'" % nameA);
for row in output:
    print (row);

#save the changes
conn.commit();

#close the cursor    
cur.close();

输出:

(0, 'dogA', 1)


过程2:

使用链表、插入多条数据excutemany()

'''Insert Many Operation'''
animalsInfoList = [(0,"dog",1),
                   (1,"cat",3),
                   (2,"pig",2)
                   ];
sql = "INSERT INTO animals (animal_id,name,age) VALUES (?,?,?)"
cur.executemany(sql,animalsInfoList) #ececute function exec only one statement

使用元组插入一条数据execute()

sql = "INSERT INTO animals (animal_id,name,age) VALUES (:id,:nm,:ag)"
cur.executemany(sql,[(4,"chicken",1)]) #ececute function exec only one statement


过程3:

防止injection attack使用?方式传参

animal_name = ("dog",);
output = cur.execute("SELECT * FROM animals where name = ?",animal_name);


过程4:

fetchone()逐行抓取:

cur.execute("SELECT * FROM animals");
while(True):
    animal = cur.fetchone();
    if(animal == None):
        break;
    print(animal);


fetchmany(num),该函数会取出num数量的元组加入到结果列表里

print ("\nfetchmany(2):");
cur.execute("SELECT * FROM animals");
while(True):
    twoAnimal = cur.fetchmany(2);
    if(len(twoAnimal) == 0):
        break;
    print(twoAnimal);
输出:














你可能感兴趣的:(Python 初步试用sqlite)