1. Connecting Mysql:import Pymysql
Conn=pymysql.connect ("localhost", "root", "password", "database name") #打开数据库 connection)
Cursor=db.cursor () #使用cursor () method to create a cursor object cursors)
2. Query data
Conn.query () Conn.commit () Conn.close () conn=pymysql.connect (=,=,=,=) cur=conn.cursor () Cur.execute () R cur: (, (Cur.rownumber)) (+ (r[]) + + (r[)) cur.close () conn.close () 3, inserting data import pymysql# Open database connection db = Pymysql.connect ("localhost", "testuser", "test123", "TESTDB" ) # use the cursor () method to get the operation cursor cursor = db.cursor () # sql INSERT statement sql = "" "Insert into employee (FIRST_NAME, last_name, age, sex, income) VALUES (' Mac ', ' Mohan ', 20, ' M ', 2000) "" "try: # Execute SQL statement cursor.execute (SQL) # commit to database execution db.commit () except: # rollback db.rollback () # If an error occurs Close database connection db.close () &nbSP; 4, create data table import pymysql# Open database connection db = pymysql.connect ("localhost", "testuser", " Test123 "," TESTDB " ) # create a Cursor object using the cursor () Method cursorcursor = db.cursor ( # Use the execute () method to execute sql, or delete cursor.execute if the table exists ("Drop table if exists employee ") # CREATE table with preprocessing statements sql = " "" create table employee ( first_name char ( NOT NULL, ) last_name char (, ) age int, sex char (1), INCOME FLOAT ) "" "Cursor.execute (SQL) # Close database connection Db.close ()
This article is from the "Python installation of various Libraries" blog, reproduced please contact the author!
Python3 version of MySQL operation