http://blog.chinaunix.net/uid-8487640-id-3183185.htmlhtml
MySQLdb是Python鏈接MySQL的模塊,下面介紹一下源碼方式安裝MySQLdb:
- 首先要下載下載:請到官方網站http://sourceforge.net/projects/mysql-python/或者點擊連接下載http://downloads.sourceforge.net/project/mysql-python/mysql-python-test/1.2.3c1/MySQL-python-1.2.3c1.tar.gz?use_mirror=nchc
- 解壓:tar zxvf MySQL-python*
- 進入文件目錄,運行如下命令:
python setup.py install
- 安裝完成,到你的python安裝目錄下的site-packages目錄裏檢查如下文件是否存在,若是存在即表明安裝成功了
Linux:MySQL_python-1.2.3c1-py2.6-linux-i686.egg
Mac OS X:MySQL_python-1.2.3c1-py2.6-macosx-10.4-x86_64.egg
注:若是碰到mysql_config not found的問題,有兩種方法解決:
1)ln -s /usr/local/mysql/bin/mysql_config /usr/local/bin/mysql_config
將mysql_confi從你的安裝目錄連接到/usr/local/bin目錄下,這樣就能夠在任意目錄下訪問了(也能夠放到/usr/bin)
2)編輯源碼文件夾的site.cfg文件,去掉#mysql_config = /usr/local/bin/mysql_config前的註釋#,修改後面的路徑爲你的mysql_config真正的目錄就能夠了。(若是不知道mysql_config在哪裏,運行命令:whereis mysql_config)
注:若是碰到import error: libmysqlclient.so.18: cannot open shared object file: No such file or directorypython
解決方法: locate or find libmysqlclient.so.18mysql
link path/libmysqlclient.so.18 /usr/lib/libmysqlclient.so.18linux
vi /etc/ld.so.conf //加入libmysqlclient.so.18 所在的目錄sql
插入: /usr/lib/數據庫
保存退出後執行/sbin/ldconfig生效macos
- 測試方法
1)運行命令python進入python運行環境
2)輸入如下python代碼進行測試
import MySQLdb
- test=MySQLdb.connect(db='mydb',host='myhost',user='u',passwd='p')
- cur = test.cursor()
- cur.execute('show databases;')
- for data in cur.fetchall():
- print data
- 3)若是你在屏幕上看到了你幾個數據庫的庫名的輸出表明你安裝成功了
- 可能碰到的問題
1)問題:ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
緣由是python沒法找到mysql目錄下的libmysqlclient_r.so.16動態庫,其實MySQLdb是調用mysql的c函數庫.因此本機上首先得安裝了mysql
而後: export LD_LIBRARY_PATH=/usr/local/mysql/lib/mysql:$LD_LIBRARY_PATH
而且將/usr/local/mysql5.1/lib/mysql 放入/etc/ld.so.conf中
/etc/ld.so.conf改後內容爲:
include ld.so.conf.d/*.conf
/usr/local/mysql5.1/lib/mysql
最後從新再測試一下,就不會有上面的問題了
MySQLdb操做:app
- import MySQLdb
- conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
- cursor = conn.cursor()
- cursor.execute(
- cursor.close();
#!/usr/bin/env pythondom
#coding=utf-8ide
##################################
#MySQLdb 示例 #
##################################
import MySQLdb
#創建和數據庫系統的鏈接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操做遊標
cursor = conn.cursor()
#執行SQL,建立一個數據庫.
cursor.execute("""create database python """)
#關閉鏈接,釋放資源
cursor.close();
建立數據庫,建立表,插入數據,插入多條數據
- import MySQLdb
- conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
- cursor = conn.cursor()
- cursor.execute(
- conn.select_db('python');
- cursor.execute(
- value = [1,"inserted ?"];
- cursor.execute("insert into test values(%s,%s)",value);
- values=[]
- for i in range(20):
- values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
- cursor.executemany(
- cursor.close();
#!/usr/bin/env python
#coding=utf-8
###################################
#MySQLdb 示例 #
##################################
import MySQLdb
#創建和數據庫系統的鏈接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操做遊標
cursor = conn.cursor()
#執行SQL,建立一個數據庫.
cursor.execute("""create database if not exists python""")
#選擇數據庫
conn.select_db('python');
#執行SQL,建立一個數據表.
cursor.execute("""create table test(id int, info varchar(100)) """)
value = [1,"inserted ?"];
#插入一條記錄
cursor.execute("insert into test values(%s,%s)",value);
values=[]
#生成插入參數值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)));
#插入多條記錄
cursor.executemany("""insert into test values(%s,%s) """,values);
#關閉鏈接,釋放資源
cursor.close();
查詢和插入的流程差很少,只是多了一個獲得查詢結果的步驟
- import MySQLdb
- conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')
- cursor = conn.cursor()
- count = cursor.execute('select * from test')
- print '總共有 %s 條記錄',count
- print "只獲取一條記錄:"
- result = cursor.fetchone();
- print result
- print 'ID: %s info: %s' % result
- print "只獲取5條記錄:"
- results = cursor.fetchmany(5)
- for r in results:
- print r
- print "獲取全部結果:"
- cursor.scroll(0,mode='absolute')
- results = cursor.fetchall()
- for r in results:
- print r
- conn.close()
默認mysqldb返回的是元組,這樣對使用者不太友好,也不利於維護
下面是解決方法
- import MySQLdb
- import MySQLdb.cursors
- conn = MySQLdb.Connect (
- host = 'localhost', user = 'root' ,
- passwd = '', db = 'test', compress = 1,
- cursorclass = MySQLdb.cursors.DictCursor, charset='utf8') // <- important
- cursor = conn.cursor()
- cursor.execute ("SELECT name, txt FROM table")
- rows = cursor.fetchall()
- cursor.close()
- conn.close()
- for row in rows:
- print row ['name'], row ['txt'] # bingo!
- # another (even better) way is:
- conn = MySQLdb . Connect (
- host = ' localhost ', user = 'root' ,
- passwd = '', db = 'test' , compress = 1)
- cursor = conn.cursor (cursorclass = MySQLdb.cursors.DictCursor)
- # ...
- # results by field name
- cursor = conn.cursor()
- # ...
- # ...results by field number