Before we passed the three articles to help you figure out how to do MySQL database learning installation SQL database has a simple understanding of the Python manipulation MySQL database, this article to introduce
MySQL Library create table, and in-depth
MySQL Database learning.
First, to create a table for the MySQL library, you must first connect to the database
Before you connect to a database, verify the following:
1. You have created the database TESTDB.
2. In the TestDB database, you have created table EMPLOYEE
The 3.EMPLOYEE fields are first_name, last_name, age, SEX, and INCOME.
4. Connect to the database TestDB use the user name "TestUser", the password is "test123", you can set your own or directly use the root user name and its password, MySQL database user authorization please use the GRANT command.
5. The Python mysqldb module is already installed on your machine.
6. If you are unfamiliar with SQL statements, you can access our basic SQL tutorials
Instance:
The following example links the MySQL TestDB database:
#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ", charset= ' UTF8 ') # Use the cursor () method to get the cursor cursor = Db.cursor () # Use the Execute method to execute the SQL statement cursor.execute (" Select VERSION () ") # Use the Fetchone () method to get a data = Cursor.fetchone () print" Database version:%s "% Data # Close the database connection Db.close ()
Execute the above script output as follows:
Database version:5.0.45
Create a database table
If a database connection exists we can use the Execute () method to create a table for the database, as shown below CREATE TABLE employee
#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ", charset= ' UTF8 ') # Use the cursor () method to get the cursor cursor = db.cursor () # If the data table already exists using the Execute () method to delete the table. Cursor.execute ("DROP table IF EXISTS EMPLOYEE") # Create Data table SQL statement sql = "" CREATE Table EMPLOYEE ( first_name CHAR) N OT NULL, last_name char (+), age INT, SEX CHAR (1), INCOME FLOAT) "" " Cursor.execute (SQL) # Close database connection Db.close ()