python MySQLdb安裝和使用


MySQLdb是python的一個標准的連接和操縱mysql的模塊。

下載地址;

https://pypi.python.org/pypi/MySQL-python/1.2.4#downloads

sourceforge地址:

http://sourceforge.net/projects/mysql-python/

說一下版本問題,去上面的網址可以看到,有2個版本MySQLdb1,MySQLdb2,默認下載的是MySqLdb2,可是到了第二版,作者又新開了一個項目叫moist

https://github.com/farcepest/moist

就是前面版本的升級,不知道作者為什么要新開一個項目。查看作者MySQLdb2的readme:

This is the legacy (1.x) version of MySQLdb. While it is still being maintained, there will not be a lot of new feature development.

TODO

  • A bugfix 1.2.4 release
  • A 1.3.0 release that will support Python 2.7-3.3

The 2.0 version is being renamed moist and lives at https://github.com/farcepest/moist

mysql python的說明文檔:

http://sourceforge.net/p/mysql-python/mysqldb-2/ci/default/tree/doc/MySQLdb.txt

*************************

我用源代碼編譯安裝時報錯,於是直接下載exe文件安裝就成功了。

通過pip安裝

$pip install MySQL-python 

我最初使用這種形式安裝的,不知道怎么回事,安裝成功了,但導入包import 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

 

import MysqlDB

報錯:mysql mportError: DLL load failed: %1 不是有效的 Win32 應用程序

操作系統:win7 64位,安裝mysqldb 后提示:ImportError DLL load failed: %1 不是有效的 Win32 應用程序,是由於安裝的32位的 MySql-python-1.2.3.win32-py2.exe,,只要改成64位版本的就可以了。

 

怎么看安裝的模塊是多少位?

MySQL-python-1.2.3.win-amd64-py2.7.exe

MySQL-python-1.2.5.win32-py2.7.exe

介個就很明顯了。

在官網:http://sourceforge.net/projects/mysql-python/ 沒有64的提供。

 

經過搜索,下載到了

MySQL-python-1.2.5.win-amd64-py2.7.exe

 

 

參考之前的文章:

Python ImportError: DLL load failed: %1 不是有效的 Win32 應用程序。

 

 

select:

import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1', port=3306,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()

最開始我連接不上:報錯

_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

conn = MySQLdb.connect(host='localhost', port=3306,user='root', passwd='longforfreedom',db='python')

import MySQLdb
try:
    conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='admin',db='mysql',port=3306)
    cur=conn.cursor()
    #cur.execute('select * from user')
    cur.execute('select version()')
    data = cur.fetchone()
    print "Databases version: %s " %  data
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

 

 

把loclhoast改為ip地址就可以了。具體原因不清楚。

創建數據庫:

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()
#執行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();

我現在插入有點問題,插入不了。

摘自doc上的話:

To perform a query, you first need a cursor, and then you can execute
queries on it::
 
c=db.cursor()
max_price=5
c.execute( """SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s """, (max_price ,)) 注意,后面一個參數為tuple
 
In this example, ``max_price=5`` Why, then, use ``%s`` in the
string? Because MySQLdb will convert it to a SQL literal value, which
is the string '5'. When it's finished, the query will actually say,
"...WHERE price < 5".
 
Why the tuple? Because the DB API requires you to pass in any
parameters as a sequence. Due to the design of the parser, (max_price)
is interpreted as using algebraic grouping and simply as max_price and
not a tuple. Adding a comma, i.e. (max_price,) forces it to make a
tuple.
 
And now, the results::
 
>>> c.fetchone()
(3L, 2L, 0L)
 
Quite unlike the ``_mysql`` example, this returns a single tuple,
which is the row, and the values are properly converted by default...
except... What's with the L's?
 為什么后面有L,long integers?
As mentioned earlier, while MySQL's INTEGER column translates
perfectly into a Python integer, UNSIGNED INTEGER could overflow, so
these values are converted to Python long integers instead.
 
If you wanted more rows, you could use ``c.fetchmany(n)`` or
``c.fetchall()``. These do exactly what you think they do. On
``c.fetchmany(n)``, the ``n`` is optional and defaults to
``c.arraysize``, which is normally 1. Both of these methods return a
sequence of rows, or an empty sequence if there are no more rows. If
you use a weird cursor class, the rows themselves might not be tuples.
 
Note that in contrast to the above, ``c.fetchone()`` returns ``None``
when there are no more rows to fetch.
 
The only other method you are very likely to use is when you have to
do a multi-row insert::
 
c.executemany(
"""INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)""",
[
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
] )
 
Here we are inserting three rows of five values. Notice that there is
a mix of types (strings, ints, floats) though we still only use
``%s``. And also note that we only included format strings for one
row. MySQLdb picks those out and duplicates them for each row.
 
其實 還可以這么寫:
value=('單人間',1,5)
cursor.execute("insert into room (roomType,hotelId,roomNum) values(%s,%s,%s)",value)
利用python百分號的威力,可以寫成:

value1='單人間'
value2=5
value3=5

cursor.execute("insert into room (roomType,hotelId,roomNum) values( '%s',%d,%d)" % (value1,value2,value3) )

insertId=conn.insert_id()
affectedRows=conn.affected_rows()
conn.commit()

 這里主要利用%后面的會替換前面的占位符。
上面的輸出:

14 insert id
1 affected rows。

這是2個很重要的方法。

 

一直困擾我的問題:下面的代碼:
import MySQLdb

def dbinsert():
    conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='sm159357',db='hotelbookown')

    cursor = conn.cursor()
    cursor.execute("select * from user")
    results=cursor.fetchall()
    for r in results:
        print r
    value=('user12','user12')
    #插入一條記錄
    cursor.execute("insert into user (username,password) values(%s,%s)",value)
     

我確實 可以運行,也不報錯,但是數據庫就是沒有插入記錄,很郁悶。在網上看到帖子說要在execute后加個

conn.commit()就可以了,果不其然,確實可以。

 

解決中午插入亂碼

在文件前面加coding=utf-8

連接時:

conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='sm159357',db='hotelbookown',charset='utf8')

中文插入時應該是這樣

a=u'中文

如果是a=’中文‘則錯誤。

 

插入多條數據(帶有int型的)都用%s 會自動轉換的。

 valueArr=[
        ('單人間',1,5),
        ('單人間',2,5),
        ('雙人間',3,5)
        ]
    cursor.executemany("insert into room (roomType,hotelId,roomNum) values(%s,%s,%s)",valueArr)
    conn.commit()

關閉方法,

cursor.close()

conn.close()

 

 

很奇怪我為什么delet無效,原因在於沒有用

 conn.commit()


測試增刪改查操作
import MySQLdb

conn = MySQLdb.connect(
                       host = '127.0.0.1',
                       port = 3306,
                       user = 'root',
                       passwd = '142857',
                       db = 'user',
                       charset = 'utf8'
                       )

cursor = conn.cursor()
sql_insert = 'insert into user_table(`id`,`name`) values(10,"name10")'
sql_update = 'update user_table set `name`="name_07" where id =7'
sql_delete = "delete from user_table where id<3 "


try:
    cursor.execute(sql_insert)
    print cursor.rowcount
    
    cursor.execute(sql_update)
    print cursor.rowcount
    
    cursor.execute(sql_delete)
    print cursor.rowcount
    
    conn.commit() except Exception as e:
    print e
    conn.rollback()

cursor.close()
conn.close()

這里特別要注意的是sql語句使用execute()方法執行后,要使用commit()方法提交處理,當事務失敗后,要調用rollback()方法進行事務的回滾。注意盡量避免使用不支持事務的存儲引擎。

使用python操作數據庫模擬銀行轉賬的功能

 

import sys
import MySQLdb

class TransferMoney():
    def __init__(self,conn):
        self.conn = conn
    

    def check_acct_available(self, acctid):
        cursor = self.conn.cursor()
        try:
            sql = 'select * from account where acctid=%s' % acctid
            cursor.execute(sql)
            print 'check_acct_available:' + sql
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception("賬號%s不存在" % acctid)
        finally:
            cursor.close()
    
    def has_enough_money(self, acctid, money):
        cursor = self.conn.cursor()
        try:
            sql = 'select * from account where acctid=%s and money > %s' % (acctid,money)
            cursor.execute(sql)
            print 'has_enough_money:' + sql
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception("賬號%s沒有足夠的錢" % acctid)
        finally:
            cursor.close()
    
    
    def reduce_money(self, acctid, money):
        cursor = self.conn.cursor()
        try:
            sql = 'update account set money=money-%s where acctid=%s' % (money,acctid)
            cursor.execute(sql)
            print 'reduce_money:' + sql
            if cursor.rowcount != 1:
                raise Exception("賬號%s減款失敗" % acctid)
        finally:
            cursor.close()
    
    
    def add_money(self, acctid, money):
        cursor = self.conn.cursor()
        try:
            sql = 'update account set money=money+%s where acctid=%s' % (money,acctid)
            cursor.execute(sql)
            print 'add_money:' + sql
            if cursor.rowcount != 1:
                raise Exception("賬號%s加款失敗" % acctid)
        finally:
            cursor.close()
    
    
    def transfer(self,source_acctid,target_acctid,money):
        try:
            self.check_acct_available(source_acctid)
            self.check_acct_available(target_acctid)
            self.has_enough_money(source_acctid,money)
            self.reduce_money(source_acctid,money)
            self.add_money(target_acctid,money)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            raise e
        
        
if __name__ == "__main__":
    source_acctid = sys.argv[1]
    target_acctid = sys.argv[2]
    money = sys.argv[3]
    print source_acctid,' ',target_acctid,' ',money
    conn = MySQLdb.connect(host='127.0.0.1',port = 3306,user = 'root',passwd='142857',db ='user',charset = 'utf8')
    tr_money = TransferMoney(conn)
    try:
        tr_money.transfer(source_acctid,target_acctid,money)
    except Exception as e:
        print u'出現問題',e
    finally:
        conn.close()  
View Code

賬戶 11 余額為110元

賬戶 12 余額為10元

執行12 11 100意為賬戶12轉給賬戶11 100元,則轉賬失敗

 

轉賬失敗那么11的錢沒增加,12的錢也不能少,回到數據的初始狀態,這就是事務的回滾。

當賬戶11轉給12賬戶100元時,可以完成操作,轉賬成功。回到數據庫刷新可以看到11的錢少了100元,12的錢增加了100元。

 

 

參考:http://blog.sina.com.cn/s/blog_7cc54c730101hal3.html

 

保證輸出沒有亂碼:

  我用了下面幾個措施,保證MySQL的輸出沒有亂麻:
   1 Python文件設置編碼 utf-8 (文件前面加上 #encoding=utf-8)
   2 MySQL數據庫charset=utf-8
   3 Python連接MySQL是加上參數 charset=utf8
   4 設置Python的默認編碼為 utf-8 (sys.setdefaultencoding(utf-8)
  mysql_test.py  

#encoding=utf-8
  import sys
  import MySQLdb
  
  reload(sys)
  sys.setdefaultencoding('utf-8')
  
  db=MySQLdb.connect(user='root',charset='utf8')
  cur=db.cursor()
  cur.execute('use mydb')
  cur.execute('select * from mytb limit 100')
  
  f=file("/home/user/work/tem.txt",'w')
  
  for i in cur.fetchall():
   f.write(str(i))
   f.write(" ")
  
  f.close()
  cur.close()

上面是linux上的腳本,windows下運行正常!
  
  注:MySQL的配置文件設置也必須配置成utf8
  
  設置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都設置默認的字符集(通常在/etc/mysql/my.cnf):
  [client]
  default-character-set = utf8
  [mysqld]
  default-character-set = utf8

 

 

 
參考:
http://blog.chinaunix.net/uid-8487640-id-3183185.html
http://www.iteye.com/topic/573092
http://hi.baidu.com/onekunp/item/80771e3fd63905be124b1440
http://www.linuxidc.com/Linux/2012-05/60353.htm

 

遇到的問題:

self.cursor=self.cursor.execute("select id from urllist where url='%s' " % url )
res=self.cursor.fetchone()

錯誤:

AttributeError: 'long' object has no attribute 'fetchone'

其實,execute select id 返回的是類似(1L,)這樣的元祖。

為什么上面錯誤,因為execute返回的select的數目count,

不用賦值。應該是這樣:

self.cursor.execute("select id from urllist where url='%s' " % url )
res=self.cursor.fetchone()

 

 

centos安裝pythondb

 

步驟如下:

#安裝MySQLdb
wget https://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.5.zip#md5=654f75b302db6ed8dc5a898c625e030c
unzip MySQL-python-1.2.5.zip
cd MySQL-python-1.2.5
chmod -R 775 *
python setup.py build

python setup.py install

 

 

mysql-python安裝時EnvironmentError: mysql_config not found

就是要找到mysql_config這個可執行文件

只要原因是沒有安裝:libmysqlclient-dev

sudo apt-get install libmysqlclient-dev

找到mysql_config文件的路徑

sudo updatedb
locate mysql_config

mysql_config的位置為:/usr/bin/mysql_config

在mysql-python源碼包下找到:setup_posix.py 文件,然后找到文件中的 mysql_config.path 將其值改為:/usr/bin/mysql_config,然后 sudo python setup.py install ,就ok了

 

_LINUX -DUNIV_LINUX
_mysql.c:29:20: fatal error: Python.h: No such file or directory
#include "Python.h"
^

安裝:

 yum install python-devel .

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM