Python資料庫操作

2021-08-21 06:31:23 字數 2530 閱讀 3592

我們之前接觸過的儲存資料的方式都是:

1.字串 2.列表 3.元組 4.字典

以上方式其實是屬於同一種方式,即將資料儲存在記憶體中

實際在開發過程中,資料儲存主要有三種形式:

1.將資料儲存到記憶體中;

優點:使用方便,讀寫速度快;

缺點:程式關閉的時候,記憶體會釋放,資料會消失;

2.將資料寫入到檔案中;

優點:資料儲存是永久性的,不易丟失;

缺點:開啟關閉檔案,運算元據都會比較麻煩;

3.將資料儲存到資料庫中;

優點:資料儲存是永久性的,操作也比較方便;

缺點:資料庫學習難度比較大;

資料庫按照性質分為兩大類:

1.關係型資料庫

資料和資料之間存在著廣泛的聯絡,例如:mysql、sqlite;

優點:通過乙個資料可以訪問到其他的資料。

3.非關係型資料庫

資料和資料之間沒有聯絡,例如:mongo

優點:資料為單獨的,資料之間的耦合度比較低,對資料進行增刪改不會影響其他資料

資料庫按照規模大小分為四種:

1.大型資料庫;例如: oracle

2.中型資料庫;例如: sqlserver

3.小型資料庫;例如: mysql

4.微型資料庫;例如: sqlite  

import sqlite3

# database

# 連線到乙個資料庫,如果資料庫存在 則連線

# 如果不存在 則建立

con = sqlite3.connect('mydb')

# 設定資料庫游標

# 游標使用來執行資料庫命令的

cursor = con.cursor()

# 新建乙個名字為my_info的表,裡面有欄位name、age和des

cursor.execute('create table if not exists my_info(name text,age int,des text)')

con.commit()

乙個專案裡面可能用到多個資料庫(絕大部分情況下只有乙個);

乙個資料庫裡面有多張表;

乙個表裡面有多個字段;

乙個字段裡面有多條資料;

往資料庫的表裡面新增資料的方法是:

cursor.execute('insert into my_info(name,age,des)values ("燼",1000,"我於殺戮之中盛放,亦如黎明中的花朵")')

con.commit()

刪除資料庫表my_info裡面的資料的方法是:

1.刪除年齡大於40的資料

cursor.execute('delete from my_info where age > 40')

con.commit()

2.刪除年齡大於40且名字為燼的資料

cursor.execute('delete from my_info where age>40 and name = "燼"')

con.commit()

3.刪除表的全部資料

cursor.execute('delete from my_info')

con.commit()

刪除整個表(慎用)

cursor.execute('drop table if exists my_info')

con.commit()

把名字燼改為德瑪西亞之力

cursor.execute('update my_info set name = "德瑪西亞之力" where name = "燼"')

con.commit()

查詢整個表:

cursor.execute('select * from my_info')
查詢name=燼的資料:

cursor.execute('select * from my_info where name = "燼"')
查詢age>30的資料:

cursor.execute('select name from my_info where age>30')
查詢到的資料需要抓取,有三種方式抓取資料:

注意:這裡抓取的資料都是上面的查詢到的資料。

1.抓取第乙個資料:

result = cursor.fetchone()
2.抓取全部的資料:

result = cursor.fetchall()
3.抓取指定數量的資料:

# result = cursor.fetchmany(2)
最後用print列印輸出即可:

print(result)

python 資料庫操作

例子1 建立乙個資料庫 coding utf 8 中文注釋 import mysqldb 建立和資料庫系統的連線 conn mysqldb.connect host localhost user root passwd 獲取操作游標 cursor conn.cursor 執行sql,建立乙個資料庫 ...

Python資料庫操作

定義 資料庫是儲存資料的倉庫,按照一定的資料模型進行組織 描述和儲存。可以以最大的程度減少冗餘度。資料庫管理系統的分類 常用的資料庫模型 支援的型別 null integer real text blob py對應的型別 none int float str bytes sqlite3模組 該模組定...

Python資料庫操作

查詢employee表中salary 工資 字段大於1000的所有資料 usr bin python coding utf 8 import mysqldb 開啟資料庫連線 db mysqldb.connect localhost testuser test123 testdb charset ut...