open cmd Enter the following code :
pip install PyMysql
If you use a development tool :pycharm, You can go right in setting
Input Project interperter Go inside to download , Click the plus sign to download the corresponding dependent package l 了
import pymysql
Tips : The following methods can be used to eliminate Pycharm Warnings in the compiler ( Just import , To wrap )
import warnings
warnings.filterwarnings("ignore")
db = pymysql.connect(" host IP Address ", " user name ", " password ", " The name of the database to connect to ")
cursor = db.cursor()
cursor.execute("SQL sentence ")
db.close()
Several functions :
def findAll():
# 1. Open database connection
db = pymysql.connect("localhost", "root", "root", "student")
# 2. Create cursor object
cursor = db.cursor()
# perform SQL Inquire about
cursor.execute("select * from user")
# Get a single piece of data
dataOne = cursor.fetchone()
# Close database connection
db.close()
def findAll():
# 1. Open database connection
db = pymysql.connect("localhost", "root", "root", "student")
# 2. Create cursor object
cursor = db.cursor()
# Query all records
cursor.execute("select * from user")
dataAll = cursor.fetchall()
print(dataAll)
# Close database connection
db.close()
Be careful : Determine whether the table name exists before creating , If there are exceptions
def createTable():
db = pymysql.connect("localhost", "root", "root", "student")
cursor = db.cursor()
# Create table SQL
sql = """create table student(sno varchar(12),name varchar(12))"""
# Perform the create table operation
cursor.execute(sql)
db.close()
def insert():
print(" perform :insert...")
db = pymysql.connect("localhost", "root", "root", "student")
cursor = db.cursor()
sql = """insert into student(sno,name)values('2018010211',' Zhang Xiaofei ')"""
try:
# Perform the operation
cursor.execute(sql)
# Commit transaction
db.commit()
# Number of switching back
count = cursor.rowcount
print(count)
print(" Submit successfully ")
except:
# Rollback on error
db.rollback()
print(" Something unusual happened ...")
db.close()
Tips : Other operations only need to be modified SQL Sentence can be used