python interact with the database

# coding=utf-8

import pymysql

# Connect to the database 
DB = pymysql.connect (Host = ' 127.0.0.1 ' ,
                     user='root',
                     password='123456',
                     Port = 3306 )
 # using the cursor () method creates a cursor object the Cursor 
the Cursor = db.cursor ()
 # use the execute () method executes SQL 
cursor.execute ( " the CREATE DATABASE testdb " ) # create the database testdb 
cursor.execute ( " SHOW DATABASES " ) # View all current data 
# tuple type, returns a list of all the records to obtain information 
Results = cursor.fetchall ()
 Print (Results)
cursor.execute ( " the USE testdb " ) # access to the database testdb 
cursor.execute ( " the CREATE TABLE testsheet (name VARCHAR (20), Sex CHAR (1), Age int (2)) " ) # Create a table named testsheet the 
cursor .execute ( " the iNSERT the iNTO testsheet (name, Sex, Age) the VALUES ( 'John Doe', 'M', 22) " ) # insertion information table testsheet 
the cursor.execute ( " the iNSERT the iNTO testsheet (name, Sex, Age ) VALUES ( 'three hundred twenty-one', 'female', 22) " )
cursor.execute ( " the SELECT * the FROM testsheet the WHERE name the LIKE '% three percent' ' ) # names include' three 'of human information query from the table testsheet 
# tuple type, returns a list of all the records to obtain information 
results = cursor.fetchall ()
 Print (Results)
cursor.execute ( " DROP TABLE testsheet " ) # delete tables testsheet 
cursor.execute ( " DROP DATABASE testdb " ) # delete the database testdb 
# operation cursor submitted to the database 
the db.commit ()
 # rollback cursor all operations 
db.rollback ( )
 # close the database connection 
db.close ()

 

Guess you like

Origin www.cnblogs.com/testlearn/p/11775829.html