折騰:html
【記錄】使用Python操做MySQL數據庫python
的過程當中,須要去安裝MySQLdb。mysql
去官網:web
http://pypi.python.org/pypi/MySQL-python/sql
看到有1.2.4和1.2.3shell
因此去最新的1.2.4:數據庫
http://pypi.python.org/pypi/MySQL-python/1.2.4windows
下載對應的編譯好的版本:app
MySQL-python-1.2.4.win32-py2.7.exewordpress
獲得1MB的
MySQL-python-1.2.4.win32-py2.7.exe
雙擊安裝:
結果出錯:
看來此x86的exe,是不支持個人win7 x64。
因此只能去下載源碼再去安裝了。
下載源碼:
而後再去解壓和安裝,結果果真出現
error: Unable to find vcvarsall.bat
的錯誤:
D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4>setup.py install
Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz
Extracting in c:\users\cli\appdata\local\temp\tmpkapo0l
Now working in c:\users\cli\appdata\local\temp\tmpkapo0l\distribute-0.6.28
Building a Distribute egg in D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4
D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4\distribute-0.6.28-py2.7.egg
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info\PKG-INFO
writing top-level names to MySQL_python.egg-info\top_level.txt
writing dependency_links to MySQL_python.egg-info\dependency_links.txt
writing MySQL_python.egg-info\PKG-INFO
writing top-level names to MySQL_python.egg-info\top_level.txt
writing dependency_links to MySQL_python.egg-info\dependency_links.txt
reading manifest file ‘MySQL_python.egg-info\SOURCES.txt’
reading manifest template ‘MANIFEST.in’
writing manifest file ‘MySQL_python.egg-info\SOURCES.txt’
installing library code to build\bdist.win-amd64\egg
running install_lib
running build_py
creating build
creating build\lib.win-amd64-2.7
copying _mysql_exceptions.py -> build\lib.win-amd64-2.7
creating build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-2.7\MySQLdb
creating build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-2.7\MySQLdb\constants
running build_ext
building ‘_mysql’ extension
error: Unable to find vcvarsall.bat
D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4>
而後參考以前的辦法,結果仍是出錯:
D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4>SET VS90COMNTOOLS=%VS100COMNTOOLS%
D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4>setup.py install
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info\PKG-INFO
writing top-level names to MySQL_python.egg-info\top_level.txt
writing dependency_links to MySQL_python.egg-info\dependency_links.txt
writing MySQL_python.egg-info\PKG-INFO
writing top-level names to MySQL_python.egg-info\top_level.txt
writing dependency_links to MySQL_python.egg-info\dependency_links.txt
reading manifest file ‘MySQL_python.egg-info\SOURCES.txt’
reading manifest template ‘MANIFEST.in’
writing manifest file ‘MySQL_python.egg-info\SOURCES.txt’
installing library code to build\bdist.win-amd64\egg
running install_lib
running build_py
copying MySQLdb\release.py -> build\lib.win-amd64-2.7\MySQLdb
running build_ext
building ‘_mysql’ extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,4,’final’,1) -D__version__=1.2.4 "-IC:\Program Files (x86)\MySQL\MySQL
Connector C 6.0.2\include" -ID:\tmp\dev_install_root\Python27_x64\include -ID:\tmp\dev_install_root\Python27_x64\PC /Tc_mysql.c /Fobuild\temp.win-amd64-2.7\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(42) : fatal error C1083: Cannot open include file: ‘config-win.h’: No such file or directory
error: command ‘"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\amd64\cl.exe"’ failed with exit status 2
D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4>
而後再參考:
所說的:
1)問題 : _mysql.c(34) : fatal error C1083: Cannot open include file: ‘config-win.h’: No such file or directory
error: command ‘」C:/Program Files/Microsoft Visual Studio 9.0/VC/BIN/cl.exe」‘ failed with exit status 2緣由 :緣由是安裝MySQL的時候沒有安裝C語言庫。
解決 :從新運行MySQL的安裝程序,選擇Modify,把「C Include Files / Lib Files」勾選上,並安裝。
去從新安裝mysql。
繼續:
【記錄】爲Python安裝MySQL數據庫模塊:MySQLdb
的折騰:
1.參考:
MySQL-python 1.2.3 for Windows and Python 2.7, 32bit and 64bit versions
得知:
python的
此處的要安裝x64仍是x86,是取決於你所安裝的Python的版本,而不是OS的版本。
因此此處去x64 win7中的cmd中確認一下python的版本:
C:\Users\CLi>python |
的確是x64的,因此的確要安裝的是x64。
2.下載對應的:
MySQL-python-1.2.3.win-amd64-py2.7.exe (1.0 MiB)
結果連接失效:「File does not exist.」
3.從:
http://www.codegood.com/downloads
找到一堆的下載,可是結果都失效了。
4.參考:
Python: How to install mysqldb on windows 7 x64?
結果最後找到的下載地址也是上面的那個失效的地址。
5.仍是參考:
Install MySQLdb for Python 2.6 in Windows 7 64-bit
和
python MySQLdb在windows環境下的快速安裝、問題解決方式
去本身編譯吧。
6.而後仍是一樣錯誤:
D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4>SET VS90COMNTOOLS=%VS100COMNTOOLS% D:\tmp\dev_tools\python\mysql\MySQL-python-1.2.4\MySQL-python-1.2.4>setup.py install |
而後參考:
Install Python-MySql on Windows 7 64-bit
看到了site.cfg內容是:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
[options]
# embedded: link against the embedded server library
# threadsafe: use the threadsafe client
# static: link against a static library (probably required for embedded)
embedded = False
threadsafe = True
static = False
# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
#mysql_config = /usr/local/bin/mysql_config
# http://stackoverflow.com/questions/1972259/mysql-python-install-problem-using-virtualenv-windows-pip
# Windows connector libs for MySQL. You need a 32-bit connector for your 32-bit Python build.
connector = C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2
|
而後注意到了,上面的編譯過程當中的include的路徑,就是此處的connector的值。
7.又在這裏:
Unofficial Windows Binaries for Python Extension Packages
找到了一個已編譯的版本的下載地址:
MySQL-python-1.2.3.win-amd64-py2.7.exe [1.1 Mb] [Python 2.7] [64 bit] [JUN 08, 2011] |
而後去安裝:
而後就能夠寫代碼去測試是否工做了。
參考:
而後用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
Function:
【記錄】爲Python安裝MySQL數據庫模塊:MySQLdb
Autor: Crifan Li
Date: 2013-04-22
-------------------------------------------------------------------------------
"""
#---------------------------------import---------------------------------------
import
MySQLdb
def
python_mysql_test():
"""
try to use mysql in python
"""
try
:
conn
=
MySQLdb.connect(host
=
'localhost'
,user
=
'root'
,passwd
=
'xxx'
,db
=
'wordpress'
,port
=
3306
)
print
"conn="
,conn;
cur
=
conn.cursor()
print
"cur="
,cur;
cur.execute(
'select * from wp_users'
)
cur.close()
conn.close()
except
MySQLdb.Error,e:
print
"Mysql Error %d: %s"
%
(e.args[
0
], e.args[
1
])
###############################################################################
if
__name__
=
=
"__main__"
:
python_mysql_test();
|
能夠顯示鏈接成功了:
D:\tmp\tmp_dev_root\python\tutorial_summary\python_mysql_test>python_mysql_test.py cur= <MySQLdb.cursors.Cursor object at 0x0000000002A54C50> |
對應的wordpress的數據庫是:
9.再去折騰新建數據項試試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
Function:
【記錄】爲Python安裝MySQL數據庫模塊:MySQLdb
Autor: Crifan Li
Date: 2013-04-22
-------------------------------------------------------------------------------
"""
#---------------------------------import---------------------------------------
import
MySQLdb
def
python_mysql_test():
"""
try to use mysql in python
"""
try
:
conn
=
MySQLdb.connect(host
=
'localhost'
,user
=
'root'
,passwd
=
'xxx'
,db
=
'test'
,port
=
3306
, charset
=
'utf8'
)
print
"conn="
,conn;
cur
=
conn.cursor()
print
"cur="
,cur;
createdDb
=
cur.execute(
'create database if not exists pythonMysql'
)
print
"createdDb="
,createdDb;
selectedDb
=
conn.select_db(
'pythonMysql'
)
print
"selectedDb="
,selectedDb;
createdTable
=
cur.execute(
'create table test(id int,info varchar(20))'
)
print
"createdTable="
,createdTable;
value
=
[
1
,
'hi rollen'
]
insertedValue
=
cur.execute(
'insert into test values(%s,%s)'
,value)
print
"insertedValue="
,insertedValue;
values
=
[]
for
i
in
range
(
20
):
values.append((i,
'hi rollen'
+
str
(i)))
insertedValues
=
cur.executemany(
'insert into test values(%s,%s)'
,values)
print
"insertedValues="
,insertedValues;
updatedInfo
=
cur.execute(
'update test set info="I am rollen" where id=3'
)
print
"updatedInfo="
,updatedInfo;
committed
=
conn.commit()
print
"committed="
,committed;
closedCur
=
cur.close()
print
"closedCur="
,closedCur;
closedConn
=
conn.close()
print
"closedConn="
,closedConn;
except
MySQLdb.Error,e:
print
"Mysql Error %d: %s"
%
(e.args[
0
], e.args[
1
])
###############################################################################
if
__name__
=
=
"__main__"
:
python_mysql_test();
|
結果以下:
D:\tmp\tmp_dev_root\python\tutorial_summary\python_mysql_test>python_mysql_test.py cur= <MySQLdb.cursors.Cursor object at 0x0000000002A54C50> D:\tmp\tmp_dev_root\python\tutorial_summary\python_mysql_test>python_mysql_test.py cur= <MySQLdb.cursors.Cursor object at 0x00000000028B7BE0> createdDb= 1 selectedDb= None createdTable= 0 insertedValue= 1 insertedValues= 20 updatedInfo= 1 committed= None closedCur= None closedConn= None |
數據庫中去看看結果:
都是能夠正常工做的。
至此,簡單的操做,到此結束。
之後就是針對要操做的數據,如何導入數據庫,如何操做數據庫了。
數據庫操做:
堅持天天學一點,天天積累一點點,做爲本身天天的業餘收穫,這個文章是我在吃飯的期間寫的,利用本身零散的時間學了一下python操做MYSQL,因此整理一下。
我採用的是MySQLdb操做的MYSQL數據庫。先來一個簡單的例子吧:
1
2
3
4
5
6
7
8
9
10
|
import
MySQLdb
try
:
conn
=
MySQLdb.connect(host
=
'localhost'
,user
=
'root'
,passwd
=
'root'
,db
=
'test'
,port
=
3306
)
cur
=
conn.cursor()
cur.execute(
'select * from user'
)
cur.close()
conn.close()
except
MySQLdb.Error,e:
print
"Mysql Error %d: %s"
%
(e.args[
0
], e.args[
1
])
|
請注意修改你的數據庫,主機名,用戶名,密碼。
下面來大體演示一下插入數據,批量插入數據,更新數據的例子吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import
MySQLdb
try
:
conn
=
MySQLdb.connect(host
=
'localhost'
,user
=
'root'
,passwd
=
'root'
,port
=
3306
)
cur
=
conn.cursor()
cur.execute(
'create database if not exists python'
)
conn.select_db(
'python'
)
cur.execute(
'create table test(id int,info varchar(20))'
)
value
=
[
1
,
'hi rollen'
]
cur.execute(
'insert into test values(%s,%s)'
,value)
values
=
[]
for
i
in
range
(
20
):
values.append((i,
'hi rollen'
+
str
(i)))
cur.executemany(
'insert into test values(%s,%s)'
,values)
cur.execute(
'update test set info="I am rollen" where id=3'
)
conn.commit()
cur.close()
conn.close()
except
MySQLdb.Error,e:
print
"Mysql Error %d: %s"
%
(e.args[
0
], e.args[
1
])
|
請注意必定要有conn.commit()這句來提交事務,要否則不能真正的插入數據。
運行以後個人MySQL數據庫的結果就不上圖了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import
MySQLdb
try
:
conn
=
MySQLdb.connect(host
=
'localhost'
,user
=
'root'
,passwd
=
'root'
,port
=
3306
)
cur
=
conn.cursor()
conn.select_db(
'python'
)
count
=
cur.execute(
'select * from test'
)
print
'there has %s rows record'
%
count
result
=
cur.fetchone()
print
result
print
'ID: %s info %s'
%
result
results
=
cur.fetchmany(
5
)
for
r
in
results:
print
r
print
'=='
*
10
cur.scroll(
0
,mode
=
'absolute'
)
results
=
cur.fetchall()
for
r
in
results:
print
r[
1
]
conn.commit()
cur.close()
conn.close()
except
MySQLdb.Error,e:
print
"Mysql Error %d: %s"
%
(e.args[
0
], e.args[
1
])
|
運行結果就不貼了,太長了。
查詢後中文會正確顯示,但在數據庫中倒是亂碼的。通過我從網上查找,發現用一個屬性有可搞定:
在Python代碼
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一個屬性:
改成:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8')
charset是要跟你數據庫的編碼同樣,若是是數據庫是gb2312 ,則寫charset='gb2312'。
下面貼一下經常使用的函數:
而後,這個鏈接對象也提供了對事務操做的支持,標準的方法
commit() 提交
rollback() 回滾
cursor用來執行命令的方法:callproc(self, procname, args):用來執行存儲過程,接收的參數爲存儲過程名和參數列表,返回值爲受影響的行數execute(self, query, args):執行單條sql語句,接收的參數爲sql語句自己和使用的參數列表,返回值爲受影響的行數executemany(self, query, args):執行單挑sql語句,可是重複執行參數列表裏的參數,返回值爲受影響的行數nextset(self):移動到下一個結果集cursor用來接收返回值的方法:fetchall(self):接收所有的返回結果行.fetchmany(self, size=None):接收size條返回結果行.若是size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據.fetchone(self):返回一條結果行.scroll(self, value, mode='relative'):移動指針到某一行.若是mode='relative',則表示從當前所在行移動value條,若是 mode='absolute',則表示從結果集的第一行移動value條.