Database operations using python

A: Why use Python to operate the database?

  1. Used to do performance testing, require large amounts of data insertion
  2. For use cases can be checked, it is provided with the cases checkpoint
  3. To avoid the mistakes manually insert data presented

II: the installation of third-party libraries Pymysql Python

In Python, if we want to connect the database, you need to use a third library pymysql, then how to install it?
Press win + r ----> input cmd-> Enter the following command to

pip install pymysql

After installation, direct import pycharm, no error if the installation was successful. (Ps: Due to foreign websites online installation generally slower, I generally use the Tsinghua source / Ali source)

Three: The basic syntax of the database

To learn how to use Python connect to the database, then the basic syntax of the database is also necessary to know da!

1. Check all the libraries: show databases;

2. Create a database: create database database name;

3. Use database: use the database name;

4. Insert the data into the table:
INSERT INTO table name (Column 1 Column ... n) values (values 1 ... n-value);

5. deletion:
Delete from table where defined conditions

6. modify operation:
Update table column names set the new value of 1 = 1 WHERE qualification

7. query:
SELECT * from table where defined conditions

Four: Python database connection

It says so much nonsense, and finally come to the question, then Python is how to operate the database it?

Here Insert Picture Description

Five: Python database operations

1. Establish a connection to the database;

2. Get the cursor

3. Execute the sql statement by the cursor

4. Get the contents of the database

5. Check the database is no need to submit the transaction
to modify, add, delete operations are required to submit the transaction .commit ()

6. Close the cursor; database

note:

  1. fetchone: each read a record
  2. fetchall: read all the data -> Results tuple is a tuple set
  3. fetchmany (10): each read line 10, according to the number read

For large amounts of data is generally not recommended fetchall, may make the database deadlock

The following is the use of Python code to query data for all grade table:
Here Insert Picture DescriptionHere Insert Picture Description
insert, modify, delete, we only need to modify the SQL statement on the line! !

Released four original articles · won praise 0 · Views 19

Guess you like

Origin blog.csdn.net/weixin_46164132/article/details/104942680