How to install and use pymysql offline to operate mysql database

1. Application background

Use python to operate the mysql database on the corporate internal network. However, python does not come with the function library pymysql for accessing the MySQL database and needs to be installed separately. There are many installations of pymysql on the Internet that require Internet support. This article mainly explains how to install pymysql offline, and briefly introduces how pymysql performs mysql operations.

pymysql is a MySQL database driver written in pure Python, based on the Python DB-API 2.0 specification. It not only supports Python 2.x version, but also supports Python 3.x version, so when using it, you need to choose the appropriate pymysql installation package according to your own Python version.

2. Environmental preparation

1.pymysql version. The Python version used in this article is python 3.9, so the pymysql version used is 0.9.3.

2.anaconda3 version. The python operating environment of this article is anaconda 2.3.1, python3.9.

3. IDE environment. This article uses the python IDE software Spyder 5.2.2 that comes with anaconda.

4.mysql version. MySQL version is 5.7, provided by wampserver 2.5. If you want to use mysql8.1 version, you can refer to the article Problems and solutions encountered in upgrading MySql database 5.7 to 8.1_wamp upgrade mysql_hongdi's blog-CSDN blog

3. Installation of pymsql

1. Download the pymsql installation package

Download address: https://mirrors.cloud.tencent.com/pypi/packages/da/15/23ba6592920e21cb40eb0fe0ea002d2b6177beb1ca8a4c1add5a8f32754d/PyMySQL-0.9.3.tar.gz#sha256=d8c059dcd81dedb85a9f03 4d5e22dcb4442c0b201908bede99e306d65ea7c8e7

Download addresses for other versions are also provided here:

PyMySQL-1.0.0.tar.gzicon-default.png?t=N7T8https://mirrors.cloud.tencent.com/pypi/packages/2b/c4/3c3e7e598b1b490a2525068c22f397fda13f48623b7bd54fb209cd0ab774/PyMySQL-1.0.0.tar.gz#sha256=b2508a7dc6b626210e52f711d2c2361d102d8d9b8b144e63b2512e748de1a49b

PyMySQL-1.1.0.tar.gzicon-default.png?t=N7T8https://mirrors.cloud.tencent.com/pypi/packages/41/9d/ee68dee1c8821c839bb31e6e5f40e61035a5278f7c1307dde758f0c90452/PyMySQL-1.1.0.tar.gz#sha256=4f13a7df8bf36a51e81dd9f3605fede45a4878fe02f9236349fd82a3f0612f96

 2. Install pyMySQL

(1) Unzip pymsql-0.9.3.tar.gz to the anaconda installation directory, assuming it is E:\Anaconda3

(2) Open the cmd command line interface, switch to E:\Anaconda3, and then enter the command python setup.py install

(3) Test whether the installation is successful. Enter the Python interpreter on the command line, enter the command >>>import pymysql and press Enter. If no error is reported, it can be considered that pymsql is installed successfully.

4. Introduction to the development of pymysql

(1) Coding process of pymysql

 1. Establish a database connection db = pymysql.connect (parameter)
        The parameters of the connect() function: host = host address or localhost, port = port number (default 3306),
                                             user = username, password = password,

                                             database=database, charaset=encoding method (default utf8)
  2. Create the cursor object cur = db.cursor()
  3. Execute the cursor method cur.execute("sql statement")
  4. Submit to the database db.commit()  
  5 .Close the cursor object cur.close()
  6.Close the database connection db.close()

(2) Query in pymysql

Adding, deleting, and modifying pymysql is relatively simple. Just put the corresponding insert, delete, and update statements into cur.execute for execution. For checking, pymysql provides several methods: fetchone, fetchall, fetchmany, which are introduced below:

1.fetchone method

Returns a single record, that is, a tuple. If there is no data, it returns None. For example:

cur.execute("select col1,col2, from mytable where id=1");

arr=cur.fetchone()

#The values ​​of col1 and col2 can be accessed through arr[0] and arr[1]

print(arr[0],arr[1])

Note: Use cursor.fetchone() multiple times in a loop to obtain the next result until it is empty.

2.fetchall method

 Return multiple records, that is, multiple tuples. If there is no result, return (). The code is as follows

cur.execute("select col1,col2, from mytable ");

arrs = cur.fetchall()
for row in arrs:
    print(row)

3.fetchmany(n)方法

To get the first n rows of data, the code is as follows:

cur.execute("select col1,col2, from mytable ");

arr3 = cur.fetchmany(3) gets the first three rows of data

(3) Use of placeholders in pymysql

The development process often requires passing parameters into SQL statements. The simplest method is to splice strings, but this method is prone to SQL injection attacks. Therefore, when developing, it is recommended to develop by passing parameters. Here we mainly introduce several methods.

Suppose you need to add records to the mytable table

Normal SQL statement: sql = "insert into mytable (col1,col2) values ​​('user1',19),('user2',20);"

1. Placeholder method:

sql = “insert into mytable (col1,col2) values (‘%s’,%f),(‘%s’,%f);”

In order to maintain a complete match with the SQL statement format, the following statement needs to be written:

sql = “insert into mytable (col1,col2) values (‘%s’,%f),(‘%s’,%f);”%('user1',19,'user2',20)

Note: This method requires adding single quotes '%s' to the string placeholder.

2. Parameter passing method:

sql = “insert into mytable (col1,col2) values (‘%s’,%f),(‘%s’,%f);”

In addition to passing sql in the execute method, the corresponding parameter list must also be passed in, as follows:

cur.execute(sql,['user1',19,'user2',20])
Note: The second parameter here will be matched sequentially according to the values ​​in the list

(4) Complete source code example

import pymysql

db = pymysql.connect(host='localhost',
                     port=3306,
                     user='user',
                     password='pwd',
                     database='mydatabase',
                     charset='utf8')
cur = db.cursor()
sql = "INSERT INTO interest (col1,col2) VALUES ('%s',%f),('%s',%f);"
try:
    cur.execute(sql, ['user1',19,'user2',20])
    db.commit()
except Exception as e:
    db.rollback()
finally:
    cur.close()
    db.close()


 

Guess you like

Origin blog.csdn.net/hongdi/article/details/133300253