Python操作MYSQL數據庫

jopen 10年前發布 | 65K 次閱讀 Python Python開發

Python是一種代表簡單主義思想的語言。閱讀一個良好的Python程序就感覺像是在讀英語一樣,盡管這個英語的要求非常嚴格!Python的這種偽代碼本質是它最大的優點之一。它使你能夠專注于解決問題而不是去搞明白語言本身。

本文介紹使用python如何操作MYSQL數據庫
一、安裝MySQLdb
    MySQLdb is an interface to the popular MySQL database server for Python. The design goals are
        1. Compliance with Python database API version 2.0(兼容python 數據庫API2.0接口)
        2. Thread-safety(線程安全)
        3. Thread-friendliness (threads will not block each other) (線程友好,線程間不會相互阻塞)

   下載地址:(可以根據需要下載window 或linux版本的MySQLdb)

   https://pypi.python.org/pypi/MySQL-python/1.2.5

        如果是windows的版本,直接運行,一路next安裝即可。
        如果是linux版本,則安裝步驟如下: 詳細可參與安裝包中的INSTALL文件
            $ tar xfz MySQL-python-1.2.1.tar.gz
            $ cd MySQL-python-1.2.1
            $ # edit site.cfg if necessary
            $ python setup.py build
            $ sudo python setup.py install # or su first

二、代碼示例:

#!/usr/bin/python
# encoding=utf-8
# Filename: mysqltest

import datetime
import MySQLdb as dbi

try:

    conn=dbi.connect(host="172.168.29.250",user='root',passwd='root',db='test',port=3306,charset='utf8')
    cur=conn.cursor()

    cur.execute("insert into test(id,name)values(5,'你好呀')")
    conn.commit()

    print "獲取數據"
    count=cur.execute('select * from test')

    print "總記錄條數%d" % count

    result=cur.fetchone()
    print "id:%d,name:%s" % result 

    results=cur.fetchmany(2)
    for r in results:
        print "id:%d,name:%s" % r
    print "------------" 

    results=cur.fetchall()
    for r in results:
        print "id:%d,name:%s" % r
    print "------------" 

    cur.scroll(0,mode='absolute')
    result=cur.fetchone()
    print "id:%d,name:%s" % result 

    print "------------"  
    print "創建數據庫表并插入數據:"
 #   cur.execute('create database if not exists python')
    conn.select_db('python')
 #   cur.execute('create table if not exists test (id int,info varchar(20))')

    value=[1,'hi rollen']
    cur.execute('insert into test values(%s,%s)',value)    
    values=[]
    print datetime.datetime.now()
    for i in range(10000):
        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()
    print datetime.datetime.now()
    print '請注意一定要有conn.commit()這句來提交事務,要不然不能真正的插入數據'

    cur.close()
    conn.close()
except dbi.Error,e:
    print 'Mysql error %d:%s' %(e.args[0],e.args[1])

三、解決入庫或顯示中文亂碼的問題

    1.設置python默認的編碼

       在D:\Program\Python27\Lib\site-packages目錄下,創建sitecustomize.py文件,內容如下:

import sys
sys.setdefaultencoding('utf-8')

      python啟動時,會自動加載sys模塊并設置默認編碼為utf-8    

 2.設置MYSQL的數據庫編碼為utf8

        將default_character-set、character-set-server的值設置為utf8

[client]
port            = 3306
socket          = /data/mysqldata/mysql/mysql.sock
default_character-set=utf8

[mysqld]
port = 3306
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES 
lower_case_table_names=1
socket          = /data/mysqldata/mysql/mysql.sock
datadir = /data/mysqldata/mysql

character-set-server = utf8

    3.將py文件的編碼設置為utf-8,并用utf-8進行保存

       # encoding=utf-8

    4.創建MYSQL數據庫連接時,增加charset參數   conn=dbi.connect(host="172.168.29.250",user='root',passwd='root',db='test',port=3306,charset='utf8')

四、常用函數

    這個連接對象也提供了對事務操作的支持,標準的方法

   commit() 提交
   rollback() 回滾

   cursor用來執行命令的方法:
   callproc(self, procname, args):用來執行存儲過程,接收的參數為存儲過程名和參數列表,返回值為受影響的行數
   execute(self, query, args):執行單條sql語句,接收的參數為sql語句本身和使用的參數列表,返回值為受影響的行數
   executemany(self, query, args):執行單挑sql語句,但是重復執行參數列表里的參數,返回值為受影響的行數
   nextset(self):移動到下一個結果集

   cursor用來接收返回值的方法:
   fetchall(self):接收全部的返回結果行.
   fetchmany(self, size=None):接收size條返回結果行.如果size的值大于返回的結果行的數量,則會返回cursor.arraysize條數據.
   fetchone(self):返回一條結果行.
   scroll(self, value, mode='relative'):移動指針到某一行.如果mode='relative',則表示從當前所在行移動value條,如果 mode='absolute',則表示從結果集的第一行移動value條.

五、參考資料

    http://mysql-python.sourceforge.net/MySQLdb.html

   http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html




 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!