One. Install the MySQL driver:
Because the MySQL server runs in a separate process and serves the network externally, it is necessary to support the MySQL driver of Python to connect to the MySQL server.
Installation drive: Easy_install Mysql-connector-python
Two. Connect to the database:
The following shows the use of Python code to connect to MySQL:
#!/usr/bin/env python#-*-coding:utf-8-*-# utility @ python# importing MySQL driver: Import mysql.connector# Be careful to set the password to your root password: c Onn = Mysql.connector.connect (user= ' root ', password= ' root ', database= ' test ', use_unicode=true) cursor = Conn.cursor () # Create User table: Cursor.execute (' CREATE table user (ID varchar (primary key, name varchar (20)) ') # Insert a row of records, note that the MySQL placeholder is%s: Cursor.execute (' INSERT into user (ID, name) values (%s,%s) ', [' 1 ', ' Michael ']) print cursor.rowcount# COMMIT transaction: Conn.commit () c Ursor.close () # execution query: cursor = conn.cursor () cursor.execute (' select * from user ') values = Cursor.fetchall () print values # [(U ' 1 ', U ' Michael ')]# close cursor and Connection:cursor.close () Conn.close ()
Python Learning Notes (15)-Python connects to MySQL database