安裝MySQLdb

MySQLdb是Python連接MySQL的模塊,下面介紹一下源碼方式安裝MySQLdb:

MySQLdb.connection():
Create a connection to the database. It is strongly recommended
    that you only use keyword parameters. Consult the MySQL C API
    documentation for more information.

    host
      string, host to connect

    user
      string, user to connect as

    passwd
      string, password to use

    db
      string, database to use

    port
      integer, TCP/IP port to connect to

    unix_socket
      string, location of unix_socket to use

    conv
      conversion dictionary, see MySQLdb.converters

    connect_timeout
      number of seconds to wait before the connection attempt
      fails.

    compress
      if set, compression is enabled

    named_pipe
      if set, a named pipe is used to connect (Windows only)

    init_command
      command which is run once the connection is created

    read_default_file
      file from which default client values are read

    read_default_group
      configuration group to use from the default file

    cursorclass
      class object, used to create cursors (keyword only)

    use_unicode
      If True, text-like columns are returned as unicode objects
      using the connection's character set.  Otherwise, text-like
      columns are returned as strings.  columns are returned as
      normal strings. Unicode objects will always be encoded to
      the connection's character set regardless of this setting.

    charset
      If supplied, the connection character set will be changed
      to this character set (MySQL-4.1 and newer). This implies
      use_unicode=True.

    sql_mode
      If supplied, the session SQL mode will be changed to this
      setting (MySQL-4.1 and newer). For more details and legal
      values, see the MySQL documentation.

    client_flag
      integer, flags to use or 0
      (see MySQL docs or constants/CLIENTS.py)

    ssl
      dictionary or mapping, contains SSL connection parameters;
      see the MySQL documentation for more details
      (mysql_ssl_set()).  If this is set, and the client does not
      support SSL, NotSupportedError will be raised.

    local_infile
      integer, non-zero enables LOAD LOCAL INFILE; zero disables

    autocommit
      If False (default), autocommit is disabled.
      If True, autocommit is enabled.
      If None, autocommit isn't set and server default is used.

windows AND linux :

pip install MySQLdb

其它情況:

安裝完成,到你的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 directory

     解決方法: locate or find libmysqlclient.so.18

     link path/libmysqlclient.so.18 /usr/lib/libmysqlclient.so.18

     vi /etc/ld.so.conf    //加入libmysqlclient.so.18 所在的目錄

     插入: /usr/lib/

     保存退出后執行/sbin/ldconfig生效

測試方法
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)如果你在屏幕上看到了你幾個數據庫的庫名的輸出代表你安裝成功了

可能碰到的問題

問題: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操作:

Python代碼

MySQLdb : create database

#!/usr/bin/env python

#coding=utf-8

###################################

#MySQLdb create database

#

##################################

import MySQLdb


#建立和數據庫系統的連接

conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')


#獲取操作游標

cursor = conn.cursor()

#執行SQL,創建一個數據庫.

cursor.execute("""create database python """)


#關閉連接,釋放資源

cursor.close();

創建數據庫,創建表,插入數據,插入多條數據

Python代碼:

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



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

查詢和插入的流程差不多,只是多了一個得到查詢結果的步驟

Python代碼:

#!/usr/bin/env python

#coding=utf-8

#

# MySQLdb 查詢

#

#######################################


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[0],result[1])

print 'ID: %s info: %s' % result


#獲取5條記錄,注意由于之前執行有了fetchone(),所以游標已經指到第二條記錄了,也就是從第二條開始的所有記錄

print "只獲取5條記錄:"

results = cursor.fetchmany(5)

for r in results:

print r


print "獲取所有結果:"

#重置游標位置,0,為偏移量,mode=absolute | relative,默認為relative,

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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,345評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,494評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,283評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,953評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,714評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,410評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,940評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,776評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,210評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,654評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,781評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,638評論 25 708
  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,526評論 6 427
  • 因為之前個人學習,耽誤了不少工作,今天一上班,馬上干起來,一會兒案頭的工作就分門別類地整理好了,然后一項一項的完成...
    舒靜心閱讀 465評論 0 0
  • 本性難移這個詞毫不夸張 縱使你在虎口中 還要爭論利益和死亡的利害關系 你流到我衣襟上的貪婪的唾液 且從目光中取出匕...
    長安之上閱讀 145評論 0 0