python資料庫操作

2022-07-24 11:33:10 字數 1592 閱讀 1356

1.連線資料庫pysql

2.讀取資料庫pandas

3.將讀取的元組資料型別轉換為列表numpy

import pymysql.cursors

db = pymysql.connect(

host='**',

port=**,

user='**',

password='**',

db='**',

charset='utf8'

)# 建立乙個游標

cursor = db.cursor()

#執行sql

cursor.execute(sql)

# 讀取資料

import pandas as pd

import numpy as np

result = cursor.fetchall()

print(result,type(result))

result1 = pd.dataframe(list(result), columns=["sku_count", "sku_pay_amount", "unit_price"])

print(result1,type(result1))

# 先使用array()將dataframe轉換一下

result2 = np.array(result1)

print(result2,type(result2))

# 再將轉換後的資料用tolist()轉成列表

result3 = result2.tolist()

print(result3,type(result3))

for i in range(0, len(result3)):

value_column = result3[i][0]

print(value_column)

1.遍歷元組集獲取所有單個元組

students=cur.fetchall()

for student in students:

print(student)

2.遍歷元組裡的所有元素輸出

students=cur.fetchall()

for student in students:

sno=student[0]

sname=student[1]

sage=student[2]

score=student[3]

print('sno':sno,'sname':sname,'age':sage,'score':score)

3.獲取一條資料——使用下標和fetchone方法

student=cur.fetchone()

print(student)

sno=student[0]

sname=student[1]

sage=student[2]

score=student[3]

print('sno':sno,'sname':sname,'age':sage,'score':score)

python 資料庫操作

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

Python資料庫操作

我們之前接觸過的儲存資料的方式都是 1.字串 2.列表 3.元組 4.字典 以上方式其實是屬於同一種方式,即將資料儲存在記憶體中 實際在開發過程中,資料儲存主要有三種形式 1.將資料儲存到記憶體中 優點 使用方便,讀寫速度快 缺點 程式關閉的時候,記憶體會釋放,資料會消失 2.將資料寫入到檔案中 優...

Python資料庫操作

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