學(xué)習(xí)了有些基本的python的東西,總想自己動(dòng)手寫(xiě)一個(gè)程序,但是寫(xiě)程序不用數(shù)據(jù)庫(kù),顯得太低端,那么python鏈接mysql怎么來(lái)操作呢?下面就為大家來(lái)詳細(xì)介紹下
我采用的是MySQLdb操作的mysql數(shù)據(jù)庫(kù)。先來(lái)一個(gè)簡(jiǎn)單的例子吧:
importMySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
cur=conn.cursor()
cur.execute('select * from user')
cur.close()
conn.close()
exceptMySQLdb.Error,e:
print"Mysql Error %d: %s"%(e.args[0], e.args[1])
請(qǐng)注意修改你的數(shù)據(jù)庫(kù),主機(jī)名,用戶(hù)名,密碼。
下面來(lái)大致演示一下插入數(shù)據(jù),批量插入數(shù)據(jù),更新數(shù)據(jù)的例子吧:
importMySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
cur=conn.cursor()
cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table test(id int,info varchar(20))')
value=[1,'hi rollen']
cur.execute('insert into test values(%s,%s)',value)
values=[]
fori inrange(20):
values.append((i,'hi rollen'+str(i)))
cur.executemany('insert into test values(%s,%s)',values)
cur.execute('update test set info="I am rollen" where id=3')
conn.commit()
cur.close()
conn.close()
exceptMySQLdb.Error,e:
print"Mysql Error %d: %s"%(e.args[0], e.args[1])
請(qǐng)注意一定要有conn.commit()這句來(lái)提交事務(wù),要不然不能真正的插入數(shù)據(jù)。
運(yùn)行之后我的MySQL數(shù)據(jù)庫(kù)的結(jié)果就不上圖了。
importMySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
cur=conn.cursor()
conn.select_db('python')
count=cur.execute('select * from test')
print'there has %s rows record'%count
result=cur.fetchone()
printresult
print'ID: %s info %s'%result
results=cur.fetchmany(5)
forr inresults:
printr
print'=='*10
cur.scroll(0,mode='absolute')
results=cur.fetchall()
forr inresults:
printr[1]
conn.commit()
cur.close()
conn.close()
exceptMySQLdb.Error,e:
print"Mysql Error %d: %s"%(e.args[0], e.args[1])
查詢(xún)后中文會(huì)正確顯示,但在數(shù)據(jù)庫(kù)中卻是亂碼的。注意這里要添加一個(gè)參數(shù)charset:
在Python代碼
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一個(gè)屬性:
改為:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8')
charset是要跟你數(shù)據(jù)庫(kù)的編碼一樣,如果是數(shù)據(jù)庫(kù)是gb2312 ,則寫(xiě)charset='gb2312'。
備注:python mysql鏈接常用函數(shù)
commit() 提交
rollback() 回滾
cursor用來(lái)執(zhí)行命令的方法:
callproc(self, procname, args):用來(lái)執(zhí)行存儲(chǔ)過(guò)程,接收的參數(shù)為存儲(chǔ)過(guò)程名和參數(shù)列表,返回值為受影響的行數(shù)
execute(self, query, args):執(zhí)行單條sql語(yǔ)句,接收的參數(shù)為sql語(yǔ)句本身和使用的參數(shù)列表,返回值為受影響的行數(shù)
executemany(self, query, args):執(zhí)行單挑sql語(yǔ)句,但是重復(fù)執(zhí)行參數(shù)列表里的參數(shù),返回值為受影響的行數(shù)
nextset(self):移動(dòng)到下一個(gè)結(jié)果集
cursor用來(lái)接收返回值的方法:
fetchall(self):接收全部的返回結(jié)果行.
fetchmany(self, size=None):接收size條返回結(jié)果行.如果size的值大于返回的結(jié)果行的數(shù)量,則會(huì)返回cursor.arraysize條數(shù)據(jù).
fetchone(self):返回一條結(jié)果行.
scroll(self, value, mode='relative'):移動(dòng)指針到某一行.如果mode='relative',則表示從當(dāng)前所在行移動(dòng)value條,如果 mode='absolute',則表示從結(jié)果集的第一行移動(dòng)value條.