python系列均基於python3.4環境
1、新建數據表
- 新建表,命名為student(id, name, score, sex, age),id為關鍵字,代碼如下:
import sqlite3 # test.db is a file in the working directory conn = sqlite3.connect("test.db") c = conn.cursor() # create tables sql = '''create table student (id int primary key, name varchar(20), score int, sex varchar(10), age int)''' c.execute(sql) # save the changes conn.commit() # close the connection with the database conn.close()
(1)如果數據庫test.db不存在的話,會自動創建數據庫test.db
(2)如果sql語句比較長的話,需要換行,又要保持格式的話,可以使用三引號(python--基礎學習(三)字符串單引號、雙引號、三引號)
2、插入數據
- 代碼示例
import sqlite3 conn = sqlite3.connect("test.db") c = conn.cursor() students = [(2, 'mark', 80, 'male', 18), (3, 'tom', 78, 'male', 17), (4, 'lucy', 98, 'female', 18), (5, 'jimi', 60, 'male', 16)] # 第一種:execute "INSERT" c.execute("insert into student(id, name, score, sex, age) values (1,'jack',80,'male',18)") # 第二種:execute multiple commands c.executemany('insert into student values (?,?,?,?,?)', students) # 第三種:using the placeholder c.execute("insert into student values (?,?,?,?,?)", (6, 'kim', 69, 'male', 16)) conn.commit() conn.close()
3、查詢
- 代碼示例
import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() # 第一種:retrieve one record c.execute('select * from student order by score desc') print(c.fetchone()) #第1條記錄 print(c.fetchone()) #第2條記錄 # 第二種:retrieve all records as a list c.execute('select * from student order by score desc') print(c.fetchall()) # 第三種:terate through the records rs = c.execute('select * from student order by score desc') for row in rs: print(row)
conn.commit()
conn.close()
- 運行結果:
#第一種 (4, 'lucy', 98, 'female', 18) (1, 'jack', 80, 'male', 18) #第二種 [(4, 'lucy', 98, 'female', 18), (1, 'jack', 80, 'male', 18), (2, 'mark', 80, 'male', 18), (3, 'tom', 78, 'male', 17), (6, 'kim', 69, 'male', 16), (5, 'jimi', 60, 'male', 16)] #第三種 (4, 'lucy', 98, 'female', 18) (1, 'jack', 80, 'male', 18) (2, 'mark', 80, 'male', 18) (3, 'tom', 78, 'male', 17) (6, 'kim', 69, 'male', 16) (5, 'jimi', 60, 'male', 16)
4、修改
- 代碼示例
import sqlite3 conn = sqlite3.connect("test.db") c = conn.cursor() sql = "update student set name='jerry' where id = 2" c.execute(sql) conn.commit() conn.close()
5、刪除
- 刪除數據,代碼示例
conn = sqlite3.connect("test.db") c = conn.cursor() c.execute('delete from student where id=2') conn.commit() conn.close()
- 刪除數據表
c.execute('drop table tableName')
(@_@)Y 學習總結到此結束,待續!