Python操作SQLite

1. 创建数据库

import sqlite3

conn = sqlite3.connect("../Database/test.db")

print("Opened database successfully.")
View Code

2.创建表

import sqlite3

conn = sqlite3.connect("../Database/test.db")

print("Opened database successfully.")


curs = conn.cursor()

curs.execute('''
            CREATE TABLE USERS(
            ID INT PRIMARY KEY NOT NULL,
            NAME TEXT NOT NULL,
            AGE INT NOT NULL,
            ADDRESS CHAR(500),
            SALARY REAL
            );
            ''')

print("Table create successfully.")

conn.commit()

conn.close()
View Code

3.插入数据

import sqlite3

conn = sqlite3.connect("../Database/test.db")

curs = conn.cursor()

curs.execute('''
        INSERT INTO USERS(ID,NAME,AGE,ADDRESS,SALARY) 
        VALUES(1,'Paul',32,'California',3200)
        ''')

curs.execute('''
        INSERT INTO USERS(ID,NAME,AGE,ADDRESS,SALARY) 
        VALUES(2,'Allen',25,'Texas',5300)
        ''')

curs.execute('''
        INSERT INTO USERS(ID,NAME,AGE,ADDRESS,SALARY) 
        VALUES(3,'Martin',40,'Norway',3600)
        ''')

curs.execute('''
        INSERT INTO USERS(ID,NAME,AGE,ADDRESS,SALARY) 
        VALUES(4,'Teddy',34,'Boston',4500)
        ''')

curs.execute('''
        INSERT INTO USERS(ID,NAME,AGE,ADDRESS,SALARY) 
        VALUES(5,'Mark',29,'Rich-Mond',3700)
        ''')

conn.commit()

conn.close()
View Code

4.查询数据

import sqlite3

conn = sqlite3.connect("../Database/test.db")


curs = conn.cursor()

cursor = curs.execute('''
            SELECT ID,NAME,AGE,ADDRESS,SALARY FROM USERS
            ''')

for row in cursor:
    print("ID =", row[0])
    print("NAME =", row[1])
    print("AGE =", row[2])
    print("ADDRESS =", row[3])
    print("SALARY =", row[4])

conn.close()
View Code

5.更新数据

import sqlite3

conn = sqlite3.connect("../Database/test.db")


curs = conn.cursor()

curs.execute('''
            UPDATE USERS SET SALARY = 4700 WHERE ID = 5
            ''')

conn.commit()

print("Total number of rows updated:", conn.total_changes)

dataRow = curs.execute('''
                SELECT ID,NAME,AGE,ADDRESS,SALARY FROM USERS WHERE ID = 5
                ''')

for row in dataRow:
    print("ID =", row[0])
    print("NAME =", row[1])
    print("AGE =", row[2])
    print("ADDRESS =", row[3])
    print("SALARY =", row[4])

conn.close()
View Code

6.删除数据

import sqlite3

conn = sqlite3.connect("../Database/test.db")

curs = conn.cursor()

curs.execute('''
            DELETE FROM USERS WHERE ID = 5
            ''')

print("Total number of delete:", conn.total_changes)
conn.commit()

conn.close()
View Code

 

posted @ 2020-10-13 17:52  航行  阅读(199)  评论(0编辑  收藏  举报