Operate mysql database with python

Database installation and connection
PyMySQL installation
pip install PyMySQL
python connection database
View Code
More parameters
Create table operation
Copy code
import pymysql

Open database connection

db = pymysql.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

Use the cursor() method to create a cursor object cursor

cursor = db.cursor()

Use execute() method to execute SQL, delete if the table exists

cursor.execute(“DROP TABLE IF EXISTS EMPLOYEE”)

Create a table using prepared statements

sql = “”“CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )”""

cursor.execute(sql)

Close database connection

db.close()
Copy code
Operation data
Insert operation
Copy code
import pymysql

Open database connection

db = pymysql.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

Use cursor() method to get 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:
cursor.execute(sql) # execute sql statement
db.commit() # Submit to the database for execution
except:
db.rollback() # If an error occurs, roll back

Close database connection

db.close()
Copy code
Another form of
query operation
Python query Mysql uses the fetchone() method to obtain a single piece of data, and uses the fetchall() method to obtain multiple pieces of data.

fetchone(): This method gets the next query result set. The result set is an object
fetchall(): receives all the returned result rows.
rowcount: This is a read-only attribute and returns the number of rows affected by the execute() method.
Copy the code
import pymysql

Open database connection

db = pymysql.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

Use cursor() method to get operation cursor

cursor = db.cursor()

SQL query

sql = “SELECT * FROM EMPLOYEE
WHERE INCOME > %s” % (1000)
try:

cursor.execute(sql)# Execute SQL statement
results = cursor.fetchall()# Get a list of all records
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3 ]
income = row[4]
# Print the result
print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s"%
(fname, lname, age, sex, income) )
except:
print ("Error: unable to fetch data")

Close database connection

db.close()
Copy code
Update operation
Copy code
import pymysql

Open database connection

db = pymysql.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

Use cursor() method to get operation cursor

cursor = db.cursor()

SQL update statement

sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX ='%c'"% ('M')
try:
cursor.execute(sql) # execute SQL statement
db.commit() # Submit to the database to execute
except
db. rollback() # Roll back when an error occurs

Close database connection

db.close()
Copy code
Delete operation
Copy code
import pymysql

Open database connection

db = pymysql.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

Use cursor() method to get operation cursor

cursor = db.cursor()

SQL delete statement

sql = "DELETE FROM EMPLOYEE WHERE AGE> %s"% (20)
try
cursor.execute(sql) # execute the SQL statement
db.commit() # submit the modification
except
db.rollback() # roll back when an error occurs # close the connection
db.close()
Copy code
Data backup
Logical backup of the database
Copy code
#Syntax:

mysqldump -h server -u username -p password database name> backup file.sql

Example #:
# single backup
the mysqldump -p123 -uroot-DB1> db1.sql
the mysqldump -uroot-DB1 -p123 table1 Table2> table1-DB1-table2.sql

#Multi-database backup
mysqldump -uroot -p123 --databases db1 db2 mysql db3> db1_db2_mysql_db3.sql

# Backup all libraries
mysqldump -uroot -p123 --all-databases> all.sql
copy the code
data recovery
copy the code
# Method a:
[@ Egon the root Backup] # MySQL -uroot--p123 </backup/all.sql

#Method 2:
mysql> use db1;
mysql> SET SQL_LOG_BIN=0; #Close the binary log, only valid for the current session
mysql> source /root/db1.sql
Copy code
transaction and lock
begin; # Open transaction
select * from emp where id = 1 for update; # Query id value, add row lock for update;
update emp set salary=10000 where id = 1; # Complete update
commit; # Submit transaction

Guess you like

Origin blog.csdn.net/shiguanggege/article/details/113791380