pip install pymysql
MySQL operation
Guide package
import pymysql
Step one: Open Database Connectivity
db = pymysql.connect (host = "database address",
the User = "username",
password = "password",
Port = "port",
Database = "database name",
charset = 'utf8 ')
Step 2: Create a cursor
cursor = db.cursor ()
The third step: Operation Database
1, create a table
# If the data table already exists using execute () method to delete the table.
cursor.execute ( "DROP TABLE IF EXISTS EMPLOYEE ")
# 创建数据表SQL语句
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
2, query data
1.Python Mysql query using either fetchone () method to obtain a single data used or fetchall () method to obtain a plurality of data.
2.fetchone (): returns the result of all the folding lines.
3.rowcount: This is a method to obtain a query result set. The result set is an object
4.fetchall (): a read-only access attribute, and return execution execute () method of the number of rows affected.
# SQL query
SQL = "the SELECT * the FROM the EMPLOYEE the WHERE INCOME> {}" format (1000).
The try:
# execute SQL statements
cursor.execute (SQL)
# get a list of all the records
Results = cursor.fetchall ()
for Row in Results :
fname = Row [0]
lname = Row [. 1]
Age = Row [2]
Sex = Row [. 3]
Income = Row [. 4]
# printing result
print ( "fname = {}, lname = {}, age = { }, sex = {}, income = {} ". format (fname, lname, age, sex, income))
except:
print("Error: unable to fecth data")
3, add data
# SQL insert statements in
SQL = "" "the INSERT the INTO the EMPLOYEE (FIRST_NAME,
the LAST_NAME, of AGE, SEX, INCOME)
the VALUES ( 'the Mac', 'Mohan', 20 is, 'M', 2000)" ""
the try:
cursor.execute (SQL)
# submitted to the database to perform
the db.commit ()
the except:
# rollback when an error occurs
db.rollback ()
4, modify data
# SQL update statement
SQL = "the UPDATE = the EMPLOYEE the SET of AGE. 1 of AGE + SEX = the WHERE '{}'" the format ( 'M').
The try:
the cursor.execute (SQL)
# submitted to the database to perform
db.commit ()
the except:
rollback when an error occurs #
db.rollback ()
5, delete data
# SQL delete statement
SQL = "DELETE the FROM the EMPLOYEE the WHERE AGE> {}" format (20).
The try:
cursor.execute (SQL)
# submitted to the database to perform
the db.commit ()
the except:
back when an error occurs # roll
db.rollback ()
Step Four: Close the cursor, the database connection
cursor.close ()
db.Close ()