連接Mysql
#coding=utf-8
#MySQLdb 示例
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫(kù)系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標(biāo)
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)庫(kù).
cursor.execute("""create database python """)
#關(guān)閉連接,釋放資源
cursor.close();
插入數(shù)據(jù)、批量插入數(shù)據(jù)
#coding=utf-8
###################################
# @author migle
# @date 2010-01-17
##################################
#MySQLdb 示例
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫(kù)系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='21ccvn')
#獲取操作游標(biāo)
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)庫(kù).
cursor.execute("""create database if not exists 21ccvn""")
#選擇數(shù)據(jù)庫(kù)
conn.select_db('21ccvn');
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)表.
cursor.execute("""create table 21ccvn(id int, info varchar(100)) """)
value = [1,"inserted ?"];
#插入一條記錄
cursor.execute("insert into test values(%s,%s)",value);
values=[]
#生成插入?yún)?shù)值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多條記錄
cursor.executemany("""insert into test values(%s,%s) """,values);
#關(guān)閉連接,釋放資源
cursor.close();
查詢,獲取一個(gè),獲取多個(gè),獲取所有記錄數(shù)
#coding=utf-8
#
# MySQLdb 查詢
#
#######################################
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='21ccvn')
cursor = conn.cursor()
count = cursor.execute('select * from test')
print '總共有 %s 條記錄',count
#獲取一條記錄,每條記錄做為一個(gè)元組返回
print "只獲取一條記錄:"
result = cursor.fetchone();
print result
#print 'ID: %s info: %s' % (result[0],result[1])
print 'ID: %s info: %s' % result
#獲取5條記錄,注意由于之前執(zhí)行有了fetchone(),所以游標(biāo)已經(jīng)指到第二條記錄了,也就是從第二條開始的所有記錄
print "只獲取5條記錄:"
results = cursor.fetchmany(5)
for r in results:
print r
print "獲取所有結(jié)果:"
#重置游標(biāo)位置,0,為偏移量,mode=absolute | relative,默認(rèn)為relative,
cursor.scroll(0,mode='absolute')
#獲取所有結(jié)果
results = cursor.fetchall()
for r in results:
print r
conn.close()