MySQLdb的安裝與使用,MySQLdb安裝使用

來源:互聯網
上載者:User

MySQLdb的安裝與使用,MySQLdb安裝使用

一、安裝

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

http://www.codegood.com/downloads

根據自己系統下載,雙擊安裝,搞定

然後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)
zzz
1436067892
('bbb', 1436067892L)
bbb
1436067892
('ccc', 33L)
ccc
33
('ddd', 44L)
ddd
44
delete 1
(('zzz', 1436067892L), ('ccc', 33L), ('ddd', 44L))


更多詳情請戳:MySQLdb User's Guide

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.