'''创建数据库中的表,在表中插入数据,获取数据并计数数据'''import sqlite3con=sqlite3.connect(':memory:')table1="""CREATE table sales (customer VARCHAR(20), product VARCHAR(40), amount float, date DATE);"""con.execute(table1)con.commit()data=[('Richard Lucas', 'Notepad', 2.50, '2014-01-02'), ('Jenny Kim', 'Binder', 4.15, '2014-01-15'), ('svetlana Crow', 'Printer', 155.75, '2014-02-03'), ('Stephen Randolph', 'Computer', 679.40, '2014-02-20')]statement="INSERT INTO sales VALUES(?,?,?,?);"con.executemany(statement,data)con.commit()query1=con.execute("SELECT * FROM sales")rows=query1.fetchall()row_counter=0for row in rows: print(row) row_counter=row_counter+1print('Number of rows in table:%d'%(row_counter))'''向表中插入csv数据'''import sqlite3import csvimport sysinput_file=sys.argv[1]con=sqlite3.connect('Database1.db')c=con.cursor() #建立数据库连接table2="""CREATE table IF NOT EXISTS suppliers (suppliers_name VARCHAR(20), invoice_number VARCHAR(20), part_number VARCHAR(20), cost float, purchase_date DATE);"""c.execute(table2)con.commit()file_reader=csv.reader(open(input_file,'r'),delimiter=',')header=next(file_reader,None)print('csv文件中的内容是:')for row in file_reader: data=[] for column in range(len(header)): data.append(row[column]) print(data) c.execute("INSERT INTO suppliers VALUES(?,?,?,?,?);",data)con.commit()print('写入的内容是:')query2=c.execute("SELECT * FROM suppliers")rows=query2.fetchall()for row in rows: print(row)'''使用csv数据更新表中的数据'''import csvimport sqlite3import sysinput_file=sys.argv[1]con=sqlite3.connect('Database2.db')c=con.cursor()table3="""CREATE table IF NOT EXISTS sales (customer VARCHAR(20), product VARCHAR(40), amount float, date DATE);"""c.execute(table3)con.commit()data=[('Richard Lucas', 'Notepad', 2.50, '2014-01-02'), ('Jenny Kim', 'Binder', 4.15, '2014-01-15'), ('svetlana Crow', 'Printer', 155.75, '2014-02-03'), ('Stephen Randolph', 'Computer', 679.40, '2014-02-20')]print('写入数据表中的数据是:')for tuple in data: print(tuple)statement="INSERT INTO sales VALUES(?,?,?,?);"c.executemany(statement,data)con.commit()file_reader=csv.reader(open(input_file,'r'),delimiter=',')header=next(file_reader,None)print('将要更新进数据表中的csv数据是:')for row in file_reader: data=[] for column in range(len(header)): data.append(row[column]) print(data) c.execute("UPDATE sales SET amount=?,date=? WHERE customer=?;",data)con.commit()query3=c.execute("SELECT * FROM sales;")rows=query3.fetchall()print('数据表中的所有数据是:')for row in rows: print(row)
总结 以上是内存溢出为你收集整理的python—sqlite全部内容,希望文章能够帮你解决python—sqlite所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)