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的問(wèn)題,有兩種方法解決:
1)ln -s /usr/local/mysql/bin/mysql_config /usr/local/bin/mysql_config
將mysql_confi從你的安裝目錄鏈接到/usr/local/bin目錄下,這樣就可以在任意目錄下訪問(wèn)了(也可以放到/usr/bin)
2)編輯源碼文件夾的site.cfg文件,去掉#mysql_config = /usr/local/bin/mysql_config前的注釋#,修改后面的路徑為你的mysql_config真正的目錄就可以了。(如果不知道m(xù)ysql_config在哪里,運(yùn)行命令: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/
保存退出后執(zhí)行/sbin/ldconfig生效
測(cè)試方法
1)運(yùn)行命令python進(jìn)入python運(yùn)行環(huán)境
2)輸入以下python代碼進(jìn)行測(cè)試
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)如果你在屏幕上看到了你幾個(gè)數(shù)據(jù)庫(kù)的庫(kù)名的輸出代表你安裝成功了
可能碰到的問(wèn)題
問(wèn)題:ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
原因是python無(wú)法找到mysql目錄下的libmysqlclient_r.so.16動(dòng)態(tài)庫(kù),其實(shí)MySQLdb是調(diào)用mysql的c函數(shù)庫(kù).所以本機(jī)上首先得安裝了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改后內(nèi)容為:
include ld.so.conf.d/*.conf
/usr/local/mysql5.1/lib/mysql
最后重新再測(cè)試一下,就不會(huì)有上面的問(wèn)題了
MySQLdb操作:
Python代碼
MySQLdb : create database
#!/usr/bin/env python
#coding=utf-8
###################################
#MySQLdb create database
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫(kù)系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標(biāo)
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)庫(kù).
cursor.execute("""create database python """)
#關(guān)閉連接,釋放資源
cursor.close();
創(chuàng)建數(shù)據(jù)庫(kù),創(chuàng)建表,插入數(shù)據(jù),插入多條數(shù)據(jù)
Python代碼:
#!/usr/bin/env python
#coding=utf-8
###################################
#MySQLdb 示例
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫(kù)系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標(biāo)
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)庫(kù).
cursor.execute("""create database if not exists python""")
#選擇數(shù)據(jù)庫(kù)
conn.select_db('python');
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)表.
cursor.execute("""create table test(id int, info varchar(100)) """)
value = [1,"inserted ?"];
#插入一條記錄
cursor.execute("insert into test values(%s,%s)",value);
values=[]
#生成插入?yún)?shù)值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多條記錄
cursor.executemany("""insert into test values(%s,%s) """,values);
#關(guān)閉連接,釋放資源
cursor.close();
#!/usr/bin/env python
#coding=utf-8
###################################
#MySQLdb 示例 #
##################################
import MySQLdb
#建立和數(shù)據(jù)庫(kù)系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標(biāo)
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)庫(kù).
cursor.execute("""create database if not exists python""")
#選擇數(shù)據(jù)庫(kù)
conn.select_db('python');
#執(zhí)行SQL,創(chuàng)建一個(gè)數(shù)據(jù)表.
cursor.execute("""create table test(id int, info varchar(100)) """)
value = [1,"inserted ?"];
#插入一條記錄
cursor.execute("insert into test values(%s,%s)",value);
values=[]
#生成插入?yún)?shù)值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)));
#插入多條記錄
cursor.executemany("""insert into test values(%s,%s) """,values);
#關(guān)閉連接,釋放資源
cursor.close();
查詢和插入的流程差不多,只是多了一個(gè)得到查詢結(jié)果的步驟
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
#獲取一條記錄,每條記錄做為一個(gè)元組返回
print "只獲取一條記錄:"
result = cursor.fetchone();
print result
#print 'ID: %s info: %s' % (result[0],result[1])
print 'ID: %s info: %s' % result
#獲取5條記錄,注意由于之前執(zhí)行有了fetchone(),所以游標(biāo)已經(jīng)指到第二條記錄了,也就是從第二條開始的所有記錄
print "只獲取5條記錄:"
results = cursor.fetchmany(5)
for r in results:
print r
print "獲取所有結(jié)果:"
#重置游標(biāo)位置,0,為偏移量,mode=absolute | relative,默認(rèn)為relative,
cursor.scroll(0,mode='absolute')
#獲取所有結(jié)果
results = cursor.fetchall()
for r in results:
print r
conn.close()
默認(rèn)mysqldb返回的是元組,這樣對(duì)使用者不太友好,也不利于維護(hù)
下面是解決方法
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