MySQLdb的安裝與使用

2021-09-22 04:50:20 字數 1893 閱讀 5020

一、安裝

安裝已編譯版本(此方法簡便快捷):

然後import mysqldb,檢視是否成功

我的,win7,32位,2.7版本

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

二、使用

#!/usr/bin/python

# encoding: utf-8

import time,mysqldb

# 開啟資料庫連線

db = mysqldb.connect("localhost","root","root","python" )

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

cursor = db.cursor()

#刪除表

sql = "drop table if exists thinkgamer"

cursor.execute(sql)

#建立sql = "create table if not exists thinkgamer(name varchar(128) primary key,created int(10))"

cursor.execute(sql)

#寫入sql = "insert into thinkgamer(name,created) values(%s,%s)"

param = ("aaa",int(time.time()))

n = cursor.execute(sql,param)

print 'insert',n

#寫入多行

sql = "insert into thinkgamer(name,created) values(%s,%s)"

param = (("bbb",int(time.time())),("ccc",33),("ddd",44))

n = cursor.executemany(sql,param)

print "insertmany",n

#更新sql= "update thinkgamer set name=%s where name='aaa'"

param = ("zzz")

n = cursor.execute(sql,param)

print "updata",n

#查詢n = cursor.execute("select * from thinkgamer")

for row in cursor.fetchall():

print row

for r in row:

print r

#刪除sql = "delete from thinkgamer where name =%s"

param = ("bbb")

n = cursor.execute(sql,param)

print "delete",n

#查詢n = cursor.execute("select * from thinkgamer")

print cursor.fetchall()

cursor.close()

#提交db.commit()

#關閉db.close()

輸出結果:

insert 1

insertmany 3

updata 1

('zzz', 1436067892l)

zzz1436067892

('bbb', 1436067892l)

bbb1436067892

('ccc', 33l)

ccc33

('ddd', 44l)

ddd44

delete 1

(('zzz', 1436067892l), ('ccc', 33l), ('ddd', 44l))

更多詳情請戳:mysqldb user's guide

Python筆記 MySQLdb安裝與使用

安裝好mysqldb後開啟pydev進行測試。1 修改pydev配置 1.1 開啟windows preferences,進行pydev設定,修改python的forced builtins 新增mysqldb後,儲存設定。2 新建乙個module進行測試 usr bin env python co...

centos 使用pip 安裝mysqldb錯誤

在centos 6.4上pip install mysql python,報錯如下 sentry kjtest111 mysql python pip install mysql python downloading unpacking mysql python running setup.py e...

關於mysqldb 的使用

1.連線 conn mysqldb.connect host,port,user,passwd 根據所要連線的資料庫進行設定 2.切換資料庫 conn.select db db name 3.關閉資料庫 conn.close 4.關於fetch的結果處理 fetch 得到的結果是tuple形式,可轉...