sqlite数据库基操
连接数据库
import sqlite3 as sql
conn=sql.connect("data.db")
创建表格
# 创建表格
# 创建表格
cur=conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS users(
user_id INT,
name TEXT,
password TEXT)""")
conn.commit()
插入数据
# 插入数据
with conn:
user_id=1
name="lzllzl"
password="09091010"
# cur.execute('''INSERT INTO users VALUES (?,?,?)''',(user_id,name,password))
cur.execute('''INSERT INTO users VALUES (:user_id,:name,:password)''',dict(user_id=user_id,name=name,password=password))
使用.csv文件增加数据
# 使用.csv文件增加数据
with open('data.csv') as f:
f.readline()
for i in range(4):
line=f.readline()
user_id,name,password=line.split(',')
with conn:
cur.execute('''INSERT INTO users VALUES (:user_id,:name,:password)''',dict(user_id=user_id,name=name,password=password))
查询数据
# 查询数据
with conn:
cur.execute('''SELECT * FROM users''')
print(cur.fetchmany(1))
print("------------")
print(cur.fetchone())
print("------------")
print(cur.fetchall())
删除数据
# 删除数据
with conn:
name='lzllzl'
cur.execute('''DELETE FROM users WHERE name=?''',(name,))
更新数据
with conn:
name='lzl'
password='8080'
cur.execute('''UPDATE users SET password=:password WHERE name=:name''',dict(name=name,password=password))
关闭数据库
conn.close()
使用pandas导入数据
import pandas as pd
from sqlalchemy import create_engine
df=pd.read_csv('./data.csv')
engine=create_engine('sqlite:///data.db')
df.to_sql('pdusers',con=engine)
标签:SQLite,name,基础,学习,user,password,id,conn,cur
From: https://www.cnblogs.com/Frey-Li/p/18113930