Ubuntu下python安裝mysqldb

Ubuntu下python安裝mysqldb(驅動)

今天呢是Ubuntu下給python安裝mysql驅動,方法以下:在終端中輸入:sudo apt-get install python-mysqldbOK,搞定,簡單吧?來測試下安裝完成以後能夠在Python解釋器中測試一下輸入 import MySQLdb #注意大小寫若是不報錯,就證實安裝成功了。

上面好簡單呀! python

程序實例: mysql

from MySQLdb import *def conn():cn=Connection('127.0.0.1','root','','test')#Connection() 函數的參數依次爲#     host(string, host to connect);#     user(string, user to connect as);#     passwd(string, password to use);#     db(string, database to use)#也能夠這樣選擇數據庫#cn.select_db('test')cur=cn.cursor()cur.execute('select * from user')#設置遊標的位置,不設置默認爲0#cur.scroll(0)row=cur.fetchone()#查詢遊標位置的一條記錄,返回值爲元 組print row[0] #輸出第一個字段內容print row[1] if __name__=='__main__':conn()

4。查詢時也可執行fetchall(),返回全部記錄爲一個元組(tuple),元組的每一個元素爲每行記錄;還有fetchmany(size) linux

5。增刪改的例子
insert: sql

cur.execute('insert into user (name,passwd) values('sparezgw','asdfasdf')')
cur.insert_id()

update: 數據庫

cur.execute('update user set passwd='asdfasdf' where name='sparezgw'')

delete: 服務器

cur.execute('delete from user where id=2')

在Ubuntu上安裝MySQLdb 函數


做者:NinGoo | 【轉載須以超連接形式標明文章原始出處和做者信息】 測試

準備用Python寫點腳本練練手,因而在Ubuntu上安裝Python的MySQLdb,本覺得很簡單的事,沒想到還碰到幾個小波折,所以記錄一下以備忘。 fetch

首先須要安裝Python-dev,不然後面編譯MySQLdb的時候會報錯,找不到頭文件: ui

building '_mysql' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC
 -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3
-I/u01/mysql/include/mysql -I/usr/include/python2.6 -c _mysql.c
-o build/temp.linux-i686-2.6/_mysql.o -DUNIV_LINUX
In file included from _mysql.c:29:
pymemcompat.h:10: fatal error: Python.h: 沒有那個文件或目錄
compilation terminated.
error: command 'gcc' failed with exit status 1

sudo apt-get install python-dev

其次須要先安裝setuptools,不然MySQLdb沒法編譯

ImportError: No module named setuptools

setuptools從這裏下載

python setup.py build


sudo python setup.py install

從這裏下載MySQLdb


修改site.cfg將mysql_config指向正確的位置

python setup.py build


sudo python setup.py install

最後還須要安裝libmysqlclient-dev,不然import模塊的時候會出錯

ImportError: libmysqlclient_r.so.16: cannot open shared object file:


 No such file or directory

sudo apt-get install libmysqlclient-dev

裝完之後,來個hello world式的簡單查詢

#!/usr/bin/env python


import MySQLdb

db=MySQLdb.connect(host="host_name",db="mysql",user="ningoo",passwd="password")
c=db.cursor()
n=c.execute("select user,host from user")
for row in c.fetchall():
        for col in row:
                print col

UBUNTU 下安裝MYSQLDB 遇到的問題2009-04-09 10:04

在個人筆記本上,直接安裝,無任何問題

昨天想在服務器上須要運行MYSQLDB,sudo apt-get install python-mysqldb提示安裝成功,但是import MySQLdb 提示找不到此模塊

sudo apt-get source python-mysqldb,想編譯一下,總也不成功,總報錯,google,了半天,

估計是庫不全,

sudo apt-get install python-all-dev

sudo apt-get install libmysqlclient15-dev

sudo apt-get install zlib1g-dev

再從新編譯 ,OK,記錄在此,以避免下次有經驗

相關文章
相關標籤/搜索