PythonMySQLdb模塊連接操作mysql數(shù)據(jù)庫實例
來源:懂視網(wǎng)
責(zé)編:小采
時間:2020-11-27 14:39:52
PythonMySQLdb模塊連接操作mysql數(shù)據(jù)庫實例
PythonMySQLdb模塊連接操作mysql數(shù)據(jù)庫實例:mysql是一個優(yōu)秀的開源數(shù)據(jù)庫,它現(xiàn)在的應(yīng)用非常的廣泛,因此很有必要簡單的介紹一下用python操作mysql數(shù)據(jù)庫的方法。python操作數(shù)據(jù)庫需要安裝一個第三方的模塊,在http://mysql-python.sourceforge.net/有下載和文檔。 由于python的數(shù)據(jù)庫模塊有
導(dǎo)讀PythonMySQLdb模塊連接操作mysql數(shù)據(jù)庫實例:mysql是一個優(yōu)秀的開源數(shù)據(jù)庫,它現(xiàn)在的應(yīng)用非常的廣泛,因此很有必要簡單的介紹一下用python操作mysql數(shù)據(jù)庫的方法。python操作數(shù)據(jù)庫需要安裝一個第三方的模塊,在http://mysql-python.sourceforge.net/有下載和文檔。 由于python的數(shù)據(jù)庫模塊有

mysql是一個優(yōu)秀的開源數(shù)據(jù)庫,它現(xiàn)在的應(yīng)用非常的廣泛,因此很有必要簡單的介紹一下用python操作mysql數(shù)據(jù)庫的方法。python操作數(shù)據(jù)庫需要安裝一個第三方的模塊,在http://mysql-python.sourceforge.net/有下載和文檔。
由于python的數(shù)據(jù)庫模塊有專門的數(shù)據(jù)庫模塊的規(guī)范,所以,其實不管使用哪種數(shù)據(jù)庫的方法都大同小異的,這里就給出一段示范的代碼:
#-*- encoding: gb2312 -*-
import os, sys, string
import MySQLdb
# 連接數(shù)據(jù)庫
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
except Exception, e:
print e
sys.exit()
# 獲取cursor對象來進(jìn)行操作
cursor = conn.cursor()
# 創(chuàng)建表
sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
cursor.execute(sql)
# 插入數(shù)據(jù)
sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)
try:
cursor.execute(sql)
except Exception, e:
print e
sql = "insert into test1(name, age) values ('%s', %d)" % ("張三", 21)
try:
cursor.execute(sql)
except Exception, e:
print e
# 插入多條
sql = "insert into test1(name, age) values (%s, %s)"
val = (("李四", 24), ("王五", 25), ("洪六", 26))
try:
cursor.executemany(sql, val)
except Exception, e:
print e
#查詢出數(shù)據(jù)
sql = "select * from test1"
cursor.execute(sql)
alldata = cursor.fetchall()
# 如果有數(shù)據(jù)返回,就循環(huán)
輸出, alldata是有個二維的列表
if alldata:
for rec in alldata:
print rec[0], rec[1]
cursor.close()
conn.close()
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
PythonMySQLdb模塊連接操作mysql數(shù)據(jù)庫實例
PythonMySQLdb模塊連接操作mysql數(shù)據(jù)庫實例:mysql是一個優(yōu)秀的開源數(shù)據(jù)庫,它現(xiàn)在的應(yīng)用非常的廣泛,因此很有必要簡單的介紹一下用python操作mysql數(shù)據(jù)庫的方法。python操作數(shù)據(jù)庫需要安裝一個第三方的模塊,在http://mysql-python.sourceforge.net/有下載和文檔。 由于python的數(shù)據(jù)庫模塊有