Pymysql is a library used in the python3.x version to connect to a MySQL server.
Installation:
Pip Install Pymysql
Database additions and deletions to change the process is similar, mainly in SQL statements. #!/usr/bin/env python3#-*- coding:utf-8 -*-import pymysql# Create a database link db = Pymysql.connect ("localhost", ' root ', ' drcom ', ' TESTDB ') #创建一个游标对象 # cursor is a data buffer opened by the system for the user, which holds the results of the SQL statement execution cursor = db.cursor () #执行sql查询, the return value is the number of data entries queried Cursor.execute ("select version ()") #获取查询数据 #fetchone return only one row at a time, That is, the next line of the result set #fetchall () Get all the rows left in the result set Data = cursor.fetchone () print ("database version:%s"%data ) #执行sql. Delete Cursor.execute ("Drop table if exists employee") if the table exists #使用预处理语句创建表sql = ' Create table employee (First_name char () not null,last_name char (),AGE Int,sex char (1), income float) "Cursor.execute (SQL) #sql插入语句insert_db = " Insert into employee (first_name,last_name,age,sex,income) VALUES (' Mac ', ' Mohan ', ' I ', ' M ', ' a ') ' Try:cursor.execute ( insert_db) #提交到数据库执行, do not perform this step, the data is not actually written to the Db.commit () except of the database: #如果发生错误则回滚db. Rollback () cursor.execute ("Select * From testdb. EMPLOYEE ") Result = cursor.fetchall () print (result) #关闭数据库db. Close ()
This article is from the "unplug the Operational Space" blog, please be sure to keep this source http://zhangdj.blog.51cto.com/9210512/1883258
python3_08. Moving MySQL