Python操做MYSQL數據庫

1、安裝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) html

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

        若是是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

2、代碼示例: mysql

#!/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])

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

    1.設置python默認的編碼 sql

       在D:\Program\Python27\Lib\site-packages目錄下,建立sitecustomize.py文件,內容以下: 數據庫

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

      python啓動時,會自動加載sys模塊並設置默認編碼爲utf-8     windows

 2.設置MYSQL的數據庫編碼爲utf8 安全

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

[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進行保存 socket

       # encoding=utf-8

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

4、經常使用函數

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

   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條.

5、參考資料

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

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

相關文章
相關標籤/搜索