Http://blog.chinaunix.net/uid-8487640-id-3183185.html
MySQLdb is the Python connection MySQL module, the following describes the source mode installation MySQLdb:
- to download the download first: please go to the official website http://sourceforge.net/projects/mysql-python/or click on the link to download http://downloads.sourceforge.net/ PROJECT/MYSQL-PYTHON/MYSQL-PYTHON-TEST/1.2.3C1/MYSQL-PYTHON-1.2.3C1.TAR.GZ?USE_MIRROR=NCHC
-
- Unzip: Tar zxvf mysql-python*
-
- into the file directory, run the following command:
python setup.py install
-
- installation complete, to The Site-packages directory in your Python installation directory checks to see if the following files exist, which means the installation succeeded
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
Note: If you encounter mysql_config not found problem, there are two ways to fix it:
1) ln-s/ Usr/local/mysql/bin/mysql_config/usr/local/bin/mysql_config
Link Mysql_confi from your installation directory to the/usr/local/bin directory, This can be accessed in any directory (also can put to/usr/bin)
2) Edit the source folder site.cfg file, remove #mysql_config =/usr/local/bin/mysql_config before the comment #, Modify the following path for your mysql_config real directory on it. (If you don't know where Mysql_config is, run the command: Whereis mysql_config)
Note: If you encounter import Error:libmysqlclient.so.18:cannot Open shared object file:no such file or directory
Workaround: Locate or find libmysqlclient.so.18
Link path/libmysqlclient.so.18/usr/lib/libmysqlclient.so.18
vi/etc/ld.so.conf //Join the directory where libmysqlclient.so.18 is located
Insertion:/usr/lib/
Save exit after execution/sbin/ldconfig effective
- Test method
1) Run command python into Python runtime environment
2) Enter the following Python code to test
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) If you see the output of the library name of several databases on your screen, you have successfully installed it.
- Problems that may be encountered
1) Problem: Importerror:libmysqlclient_r.so.16:cannot Open Shared object file:no such file or directory
The reason is that Python cannot find the libmysqlclient_r.so.16 dynamic library under the MySQL directory, in fact MySQLdb is the C function library that calls MySQL. So the first thing on this machine is to install MySQL.
Then: Export ld_library_path=/usr/local/mysql/lib/mysql: $LD _library_path
and put/usr/local/mysql5.1/lib/mysql into/etc/ld.so.conf.
The contents of the/etc/ld.so.conf after the change are:
Include ld.so.conf.d/*.conf
/usr/local/mysql5.1/lib/mysql
The last test again, there will be no problem.
MySQLdb Operation:
Python code
- #!/usr/bin/env python
- #coding =utf-8
- ###################################
- #MySQLdb Example
- #
- ##################################
- Import MySQLdb
- #建立和数据库系统的连接
- conn = MySQLdb.connect (host=' localhost ', user=' root ', passwd=' longforfreedom ')
- #获取操作游标
- cursor = Conn.cursor ()
- #执行SQL, create a database.
- Cursor.execute ("" "Create Database Python" ")
- #关闭连接, freeing up resources
- Cursor.close ();
#!/usr/bin/env python
#coding =utf-8
##################################
#MySQLdb Example #
##################################
Import MySQLdb
#建立和数据库系统的连接
conn = MySQLdb.connect (host= ' localhost ', user= ' root ', passwd= ' longforfreedom ')
#获取操作游标
cursor = Conn.cursor ()
#执行SQL, create a database.
Cursor.execute ("" "Create Database Python" ")
#关闭连接, freeing up resources
Cursor.close ();
Create a database, create a table, insert data, insert multiple data
Python code:
- #!/usr/bin/env python
- #coding =utf-8
- ###################################
- #MySQLdb Example
- #
- ##################################
- Import MySQLdb
- #建立和数据库系统的连接
- conn = MySQLdb.connect (host=' localhost ', user=' root ', passwd=' longforfreedom ')
- #获取操作游标
- cursor = Conn.cursor ()
- #执行SQL, create a database.
- Cursor.execute ("" "CREATE database if not exists Python " ")
- #选择数据库
- conn.select_db (' python ');
- #执行SQL, create a data table.
- Cursor.execute ("" "CREATE TABLE test (ID int, info varchar )" "")
- Value = [1,"inserted?"];
- #插入一条记录
- Cursor.execute ("INSERT into test values (%s,%s)", value);
- Values=[]
- #生成插入参数值
- For I in range:
- Values.append ((i,' Hello mysqldb, I am recoder ' + str (i)))
- #插入多条记录
- Cursor.executemany ("" "insert INTO test values (%s,%s)" ", values);
- #关闭连接, freeing up resources
- Cursor.close ();
#!/usr/bin/env python
#coding =utf-8
###################################
#MySQLdb Example #
##################################
Import MySQLdb
#建立和数据库系统的连接
conn = MySQLdb.connect (host= ' localhost ', user= ' root ', passwd= ' longforfreedom ')
#获取操作游标
cursor = Conn.cursor ()
#执行SQL, create a database.
Cursor.execute ("" "CREATE database if not exists Python" ")
#选择数据库
conn.select_db (' Python ');
#执行SQL, create a data table.
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);
#关闭连接, freeing up resources
Cursor.close ();
The process of querying and inserting is similar, just one more step to get the results of the query
Python code:
- #!/usr/bin/env python
- #coding =utf-8
- #
- # MYSQLDB Query
- #
- #######################################
- Import MySQLdb
- conn = MySQLdb.connect (host=' localhost ', user=' root ', passwd=' longforfreedom ', db=' python ')
- cursor = Conn.cursor ()
- Count = Cursor.execute (' select * from Test ')
- Print ' has a total of%s records ', Count
- #获取一条记录, each record is returned as a single tuple
- Print "Get only one record:"
- result = Cursor.fetchone ();
- Print result
- #print ' ID:%s info:%s '% (Result[0],result[1])
- Print ' ID:%s info:%s '% result
- #获取5条记录, note that because Fetchone () was previously executed, the cursor already refers to the second record, that is, all records starting from the second bar
- Print "Get only 5 records:"
- Results = Cursor.fetchmany (5)
- For R in results:
- Print R
- Print "Get all results:"
- #重置游标位置, 0, offset, Mode=absolute | Relative, default is relative,
- Cursor.scroll (0,mode=' absolute ')
- #获取所有结果
- Results = Cursor.fetchall ()
- For R in results:
- Print R
- Conn.close ()
The default MySQLdb returns a tuple, which is not friendly to the user and is not conducive to maintenance
Here's how it's resolved
- 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) 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
MYSQLDB Installation and use 2