python连接sqlite数据库的代码_Python连接SQLite数据库代码

import sqlite3

# create database

conn = sqlite3.connect('test.db') #不存在就创建后再打开

print ("Opened database successfully")

conn.execute('''''CREATE TABLE COMPANY

(ID INT PRIMARY KEY NOT NULL,

NAME TEXT NOT NULL,

AGE INT NOT NULL,

ADDRESS CHAR(50),

SALARY REAL);''')

print ("Table created successfully")

conn.close()

# inset data into database

conn = sqlite3.connect('test.db')

print ("Opened database successfully")

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \

VALUES (1, 'Paul', 32, 'California', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \

VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \

VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \

VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");

conn.commit()

print ("Records created successfully")

conn.close()

# select from database

conn = sqlite3.connect('test.db')

print ("Opened database successfully")

cursor = conn.execute("SELECT id, name, address, salary from COMPANY")

for row in cursor:

print ("ID = %d" % row[0])

print ("NAME = %s" % row[1])

print ("ADDRESS = %s" % row[2])

print ("SALARY = %d" % row[3])

print("\n")

print ("Operation done successfully")

conn.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值