Python 3.6 Simple operation of three instances of the Mysql database
- 2020-12-20 03:39:27
- OfStack
Install pymysql
Reference: https: / / github com/PyMySQL/PyMySQL /
pip install pymsql
Example 1
import pymysql
# Create a connection
# The parameters correspond in turn to the server address, username, password, and database
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')
# Create a cursor
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# Execution statement returns the number of affected rows
effect_row = cursor.execute("select * from course")
print(effect_row)
# Get all the data
result = cursor.fetchall()
result = cursor.fetchone() # To obtain the 1 A data
result = cursor.fetchone() # To obtain the 1 Three data points (on 1 On the basis of)
# cursor.scroll(-1, mode='relative') # Relative position shift
# cursor.scroll(0,mode='absolute') # Absolute position shift
# Commit, otherwise the newly created or modified data cannot be saved
conn.commit()
# Close the cursor
cursor.close()
# Close the connection
conn.close()
Example 2
import pymysql
# Establish a connection
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')
# Create a cursor
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# insert 1 The data %s Is a placeholder Placeholders are separated by commas
effect_row = cursor.execute("insert into course(cou_name,time) values(%s,%s)", ("Engilsh", 100))
print(effect_row)
conn.commit()
cursor.close()
conn.close()
Example 3
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
conclusion