"""创建数据库文件及连接"""
import sqlite3
conn = sqlite3.connect('test.db')
cur = conn.cursor()
import sqlite3
conn = sqlite3.connect('d:/pythonss/test.db')
cur = conn.cursor()
cur.execute('''CREATE TABLE Inventory
( ID INT,
AU TEXT,
Model CHAR(16),
Locator CHAR(12),
Hold CHAR(1),
Onhand INT);''')
cur.close()
conn.close()
import sqlite3
conn = sqlite3.connect('d:/pythonss/test.db')
cur = conn.cursor()
cur.execute("drop table Inventory")
conn.commit()
import sqlite3
l1 = []
l2 = []
l3 = []
d1 = {}
if os.path.isfile('d:/pythonss/fnd_gfm.tsv'): #先确认文件是否存在
with open('d:/pythonss/fnd_gfm.tsv','r+') as fnd:
l1 = list(fnd) #直接把文件读取成列表一行作为一个元素,写入 l1
for i in range(len(l1)):# 用for循环读取文件,并根据tab切割成列表
# 用split 先切割掉行末的换行符,再用tab字符切割成列表
l2.append((l1[i].split('\n')[0].split('\t')[:16])) # 把每行切割成元素,放入l2
#生成嵌套字典的列表的练习(非必须)
for k in range(len(l2)): # l2 中一共多少 列表元素
for i in range(len(l2[0])): # 每个子列表 包含多少元素
d1[l2[0][i]] = l2[k+1][i] #第一行作为键,第二行开始作为值
l3.append(d1)
# print (l3[k],"\n") # print输出数据量太大的时候报错
# print (l2[k],"\n")
import sqlite3
conn = sqlite3.connect('d:/pythonss/test.db')
cur = conn.cursor()
# 用format函数写sql写入指令时候 sql语句的 values 要用单引号括起来
for i in range(1,len(l2)):
cur.execute("INSERT INTO Inventory (ID,AU,Model,Locator,Hold,Onhand) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')".format(l2[i][0],l2[i][1],l2[i][2],l2[i][3],l2[i][4],l2[i][5]))
# 这是用% 方式写入数据库的语法格式
# cur.execute("insert into student (name,age,sex)" "values('%s','%d','%s')" %(l1[0][0],l1[0][1],l1[0][2]))
cur.close()
conn.close()
import sqlite3
conn = sqlite3.connect('d:/pythonss/test.db')
cur = conn.cursor()
##删除数据
# r = cur.execute('delete from inventory where ID=0')
# conn.commit() ##提交事务
##执行查询
cur.execute('select * from Inventory')
r = cur.fetchall() ##获取数据
print (r)
cur.close()
conn.close()
import sqlite3
conn = sqlite3.connect('d:/pythonss/test.db')
cur = conn.cursor()
cur.execute("drop table Inventory")
conn.commit()
cur.close()
conn.close()
import sqlite3
conn = sqlite3.connect('test.db') ##创建数据库连接
cur = conn.cursor() ##获取数据库游标
#cur.execute(creat table student(name,age,sex))
l1 = [['jee',21,'F'],['jee',21,'F'],['jee',21,'F']]
# cur.execute("insert into student (name,age,sex)" "values('%s','%d','%s')" %(l1[0][0],l1[0][1],l1[0][2])) ##执行添加sql
cur.execute("insert into student (name,age,sex)" "values('{0[0][0]}','{0[0][1]}','{0[0][2]}')".format(l1)) ##执行添加sql
cur.execute('select * from student') ##执行查询sql
r = cur.fetchall() ##获取数据
print (r)
r = cur.execute('delete from student where age = 20') ##删除
conn.commit() ##提交事务
cur.close() ##关闭游标
conn.close() ##关闭数据库连接