python系列均基于python3.4环境
1、新建数据表
import sqlite3
conn = sqlite3.connect("test.db")
c = conn.cursor()
sql = '''create table student (id int primary key, name varchar(20), score int, sex varchar(10), age int)'''
c.execute(sql)
conn.commit()
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)]
c.execute("insert into student(id, name, score, sex, age) values (1,'jack',80,'male',18)")
c.executemany('insert into student values (?,?,?,?,?)', students)
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()
c.execute('select * from student order by score desc')
print(c.fetchone()) #第1条记录
print(c.fetchone()) #第2条记录
c.execute('select * from student order by score desc')
print(c.fetchall())
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 学习总结到此结束,待续!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章