The 3.x of the Python language is completely not forward compatible, which leads us to use the library in the python2.x, and Python3 will not be used. For example MySQLdb
1. Install Pymysql
Pymysql is a substitute for the mysqldb in the PYTHON3 environment, enters the command line, installs with Pip Pymysql
Pip Install Pymysql3
2. Use of Pymysql
Add the following two lines at the beginning of the. py file that we need to use the database
Import Pymysql
Pymysql.install_as_mysqldb ()
The first line is the introduction of Pymysql, the second line is to take care of the habit of using it as a mysqldb
Linux under Python connection MySQL database method
To connect to the database name is HHH, the user name is Tom, the connected datasheet is Data_import, where the DATA_IMPORT data structure is as follows (5 properties):
mysql> desc Data_import;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| ID | char (10) | YES | | NULL | |
| name | char (10) | YES | | NULL | |
| Age | char (10) | YES | | NULL | |
| Address | varchar (15) | YES | | NULL | |
| Hobby | varchar (15) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
5 rows in Set (0.01 sec)
Linux under Python connect MySQL database complete routines:
#!/usr/bin/python
Import mysqldb #导入库
conn = MySQLdb.connect (host= "127.0.0.1", user= "Tom", passwd= "123", db= " HHH ")
#conn = MySQLdb.connect (' localhost '," Tom "," 123 "," HHH ") #连接函数
cur = conn.cursor () #获得指向当前数据库的指针
# Cur.execute (' Show Tables; ')
Cur.execute ("select * from Data_import;") #用execute () method executes the SQL statement
result = Cur.fetchall () #用fetchall () method gets the row information for the record in result
:
print '%s \t% s \t%s \t%s \t%s "% record# formatted output
cur.close () #关闭指针对象
Run results (partial):
[Root@localhost python]#./python_mysql.py
1 TOM Beijing Football
2 LIU Heibei Football
3 JIM Shandong Football
4 HAN Beijing Football
5 MENG Beijing Tennis
1 TOM Beijing Football
All right, this article introduces all the content, I hope this article will be helpful to share.