1. To enable Python to operate the MySQL database, first install the MySQL-python package. You can run the following command on CentOS to install the package:
[Python]
- $ Sudo yum install MySQL-python
2. Leave nothing to say. Take two steps. The following program creates a connection to the mysql database, executes a simple query, and prints the query result.
[Python]
- ImportMySQLdb
- Conn = MySQLdb. connect (host ="172.17.23.121", User ="Fkong", Passwd ="Fkong", Db ="Fkong")
- Cursor = conn. cursor ()
- Cursor.exe cute ("Select version ()")
- Row = cursor. fetchone ()
- Print "MySQL server version :", Row [0]
- Cursor. close ()
- Conn. close ()
3. The following is a database table creation and insertion Operation.
[Python]
- ImportMySQLdb
- Conn = MySQLdb. connect (host ="172.17.23.121", User ="Fkong", Passwd ="Fkong", Db ="Fkong")
- Cursor = conn. cursor ()
- Cursor.exe cute ("""
- CREATE TABLE TEST
- (
- Id int,
- COL1 VARCHAR (40 ),
- COL2 VARCHAR (40 ),
- COL3 VARCHAR (40)
- )
- """)
- Cursor.exe cute ("""
- Insert into test (ID, COL1, COL2, COL3)
- VALUES
- (1, 'A', 'B', 'C '),
- (2, 'A', 'bb ', 'cc '),
- (3, 'aaa', 'bbb ', 'ccc ')
- """)
- Conn. commit ()
- Cursor. close ()
- Conn. close ()
4. next let's look at the query. there are usually two ways to query: one is to use cursor. fetchall () is used to obtain all query results and then iterate over one row. fetchone () gets a record until the obtained result is null. Let's take a look at the following example:
[Python]
- ImportMySQLdb
- Conn = MySQLdb. connect (host ="172.17.23.121", User ="Fkong", Passwd ="Fkong", Db ="Fkong")
- Cursor = conn. cursor ()
- Cursor.exe cute ("SELECT * from test")
- Rows = cursor. fetchall ()
- ForRowInRows:
- Print "% D, % s"% (Row [0], Row [1], Row [2], Row [3])
- Print "Number of rows returned: % d"% Cursor. rowcount
- Cursor.exe cute ("SELECT * from test")
- While(True):
- Row = cursor. fetchone ()
- IfRow =None:
- Break
- Print "% D, % s"% (Row [0], Row [1], Row [2], Row [3])
- Print "Number of rows returned: % d"% Cursor. rowcount
- Cursor. close ()
- Conn. close ()