python下運算元據庫

2021-08-03 07:38:04 字數 2572 閱讀 8070

在windows平台上安裝mysql模組用於python開發

用python連線mysql的時候,需要用的安裝版本,原始碼版本容易有錯誤提示。下邊是打包了32與64版本。

mysql-python-1.2.3.win32-py2.7.exe

mysql-python-1.2.3.win-amd64-py2.7.exe

我使用的為window10 64,故安裝了64位版本

python 標準資料庫介面為 python db-api,python db-api為開發人員提供了資料庫應用程式設計介面

db-api 是乙個規範. 它定義了一系列必須的物件和資料庫訪問方式, 以便為各種各樣的底層資料庫系統和多種多樣的資料庫介面程式提供一致的訪問介面 。

python的db-api,為大多數的資料庫實現了介面,使用它連線各資料庫後,就可以用相同的方式操作各資料庫。

python db-api使用流程:

mysqldb 是用於python鏈結mysql資料庫的介面

在python下執行 

import

mysqldb

若不出錯,則mysql模組安裝成功

建立資料庫 testdb.

在testdb資料庫中建立表 employee,進行增刪改查操作。

對於支援事務的資料庫, 在python資料庫程式設計中,當游標建立之時,就自動開始了乙個**的資料庫事務。

commit()方法游標的所有更新操作,rollback()方法回滾當前游標的所有操作。每乙個方法都開始了乙個新的事務

#coding:utf-8

#引用模組

import mysqldb as mdb

#開啟資料庫連線

db = mdb.connect("localhost","root","chejian","testdb");

#獲取操作游標

cursor = db.cursor()

#若表存在,則刪除。。。 當不存在時,這兒執行後的警告並不影響以後語句的執行

cursor.execute("drop table if exists employee")

#建立資料庫的sql語句

sql = """create table employee (

first_name char(20) not null,

last_name char(20),

age int ,

*** char(1),

income float)"""

cursor.execute(sql)

#插入記錄 可以使用變數向sql語句中傳遞引數

sql ="""insert into employee(first_name,last_name,age,***,income) values('mac','mohan',20,'m',2000)"""

sql1 ="""insert into employee(first_name,last_name,age,***,income) values('freebsd','mohan',19,'m',1000)"""

try:

cursor.execute(sql)

cursor.execute(sql1)

#當對資料庫資料改變時,提交到資料庫執行

db.commit()

except:

#若有錯誤,則回滾

db.rollback()

#資料庫查詢

sql = "select * from employee \

where income > '%d' " %(500)

try:

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=%d,***=%s,income=%d " % \

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

except:

print "error: unable to fetcg data"

#更新資料庫

sql = "update employee set age = age + 1 where *** = '%c'" % ('m')

try:

cursor.execute(sql)

db.commit()

except:

db.rollback()

#刪除操作

sql = "delete from employee where age > '%d' " % (20)

try:

cursor.execute(sql)

db.commit()

except:

db.rollback()

#關閉資料庫連線

db.close()

python運算元據庫

資料庫的操作在現在的python裡面已經變得十分的好用,有了一套api標準.下面的就是講講如何的去使用這套框架定義.此框架包含以下部分 connect parameters.其中的引數格式如下 dsn 資料來源名稱 user 使用者名稱 可選 password 密碼 可選 host 主機名 可選 d...

python 運算元據庫

目的 通過excel定義檢查指標項,然後通過python讀取指標,通過oracle sqlplus工具去執行獲取具體巡檢結果。unicode utf 8 coding utf 8 import os import sys import xlrd import paramiko reload sys ...

python運算元據庫

python運算元據庫都是通過資料庫驅動取操作的。現在主要有兩張,一種是通過pymysql,還有一種是通過sqlalchemy。在這裡可能還會有人說還有mysqldb模組也可以操作。確實是的,但是mysqldb對python3已經不支援了,所以這裡我就不討論了。第一種pymysql pymysql幫...