Python資料庫操作

2021-09-11 20:56:53 字數 975 閱讀 9221

查詢employee表中salary(工資)字段大於1000的所有資料:

#!/usr/bin/python 

# -*- coding: utf-8 -*-

import mysqldb

# 開啟資料庫連線

db = mysqldb.connect("localhost", "testuser", "test123", "testdb", charset='utf8' )

# 使用cursor()方法獲取操作游標

cursor = db.cursor()

# sql 查詢語句

sql = "select * from employee \

where income > %s" % (1000)

try:

# 執行sql語句

cursor.execute(sql)

# 獲取所有記錄列表

results = cursor.fetchall()

for row in results:

fname = row[0]

lname = row[1]

age = row[2]

*** = row[3]

income = row[4]

# 列印結果

print "fname=%s,lname=%s,age=%s,***=%s,income=%s" % \

(fname, lname, age, ***, income )

except:

print "error: unable to fecth data"

# 關閉資料庫連線

db.close()

以上指令碼執行結果如下:
fname=mac, lname=mohan, age=20, ***=m, income=2000

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模組 該模組定...