Sqlite3是Python內置的一個輕量級數(shù)據(jù)庫 數(shù)據(jù)庫是用于保存大量而定, 格式統(tǒng)一的數(shù)據(jù), 比如保存name, age, sex, score. 數(shù)據(jù)庫內部的結構是由多張表table構成, 表中是由多個字段構成. """ 1. 先連接到數(shù)據(jù)庫文件 2. 進行數(shù)據(jù)的寫入或讀取 3. 關閉數(shù)據(jù)庫 """ import sqlite3 1> 連接數(shù)據(jù)庫 connect( ): 負責連接數(shù)據(jù)庫文件, 當數(shù)據(jù)文件不存在時, 會默認在當前目錄下創(chuàng)建一個新的數(shù)據(jù)庫文件 # connect = sqlite3.connect('database.db') 2> 要操作數(shù)據(jù)庫, 先獲取數(shù)據(jù)庫游標cursor, 通過cursor來操作表, 對表進行增刪改查的操作 # cursor = connect.cursor( ) 3> 向數(shù)據(jù)庫database.db中添加一張表table 聲明創(chuàng)建表的SQL語句 Student表中四個字段: id name age score INTEGER(integer): 整數(shù)類型 TEXT: 文本類型 PRIMARY KEY(primary key): 給id添加的約束, 將id作為主鍵. 主鍵是唯一的, 不允許重復, 主要是用于給這條數(shù)據(jù)設置一個唯一的標識, 方便查找和定位. 而name/age/score的值可能會重復, 所以不能作為主鍵 # create_student_table = "CREATE TABLE Student (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, score FLOAT)" # 執(zhí)行創(chuàng)建表的sql語句 cursor.execute(create_student_table) # 向表中插入數(shù)據(jù) insert_sql="INSERT INTO Student(name, age, score)VALUES('李四', 30, 80.5)" # 修改表中的數(shù)據(jù) WHERE: 后面跟的是篩選條件 update_sql = "UPDATE Student SET name='%s', age=%d WHERE id=1" % ('王五', 100) cursor.execute(update_sql) # 查詢表中的數(shù)據(jù) # *表示所有數(shù)據(jù) select_sql = "SELECT * FROM Student" res = cursor.execute(select_sql) for x in res: print(x) # 刪除表中的數(shù)據(jù) # 將id=1的數(shù)據(jù)刪除 delete_sql = "DELETE FROMO Student WHERE id=1" cursor.execute(delete_sql) # 執(zhí)行提交的操作 connect.commit() # 關閉游標 cursor.close() # 關閉數(shù)據(jù)庫 connect.close() |
|
來自: 昵稱62125662 > 《SQLite》