pymysql of Python series modules operates MySQL database

Table of contents

1. Install pymysql

Two, connect to the database

3. Database operation

3.1 Query

3.2 update

3.3 Batch update using loop


 Learning record of Python series articles: 

Windows environment installation and configuration of Python series

Variables and operators of Python series

Judgment and cycle of Python series - Blog - CSDN Blog

Python series of strings and lists - blog driving tractor home - CSDN blog

File Operations and Functions of the Python Series

Detailed explanation of the standard library OS of Python series modules - Programmer Sought

Detailed explanation of the standard library re of Python series modules - Programmer Sought

Detailed explanation of the standard library json of Python series modules - Programmer Sought

Detailed explanation of the standard library shutil of Python series modules - Programmer Sought


1. Install pymysql


Enter import pymysql in Pycharm, click Install according to the prompt, and the module will be installed to the lib directory of the default Python installation directory. The following is the path of the pymysql module I installed.

or use pip


Two, connect to the database


Use the connect function to create a connection object. This connection object provides operations such as closing the database and transaction rollback. The
general parameters are: host, user, password, port (default is 3306), database (the name of the database you want to connect to)

connect() method parameters

Parameter Description:

                   parameter

                       illustrate

host=

Database connection address

user=

database username

password=

database password

database=

The name of the database to connect to

port=3306

Connection port, default 3306

charset=utf8

Set the character set, usually utf8

connect_timeout=10

The connection database timeout time, generally defaults to 10 seconds

dsn

Data source name, given this parameter indicates database dependency

max_allowed_packet
 16 * 1024 * 1024
autocommit False autocommit defaults to false

Common methods for connecting objects :

method name

illustrate

cursor()

Get the cursor object, operate the database, such as performing DML operations, calling stored procedures, etc.

commit()

commit transaction

rollback()

rollback transaction

close()

close database connection

Common methods of cursor cursor objects

method name

illustrate

execute(query)

Execute database operations, such as sql statements or database commands

executemany(query,params)

For batch operations, such as: batch update

fetchone()

Get the next record in the query result set

fetchmany(size)

Get the specified number of records in the query result set, size defaults to 1

fetchall()

Get all records in the query result set

nextset()

Skip to the next available result set

close()

close the current cursor object


3. Database operation


3.1 Query


import pymysql
# 创建数据库连接对象
db = pymysql.connect(host="192.168.2.211",
                     user="root",
                     password="winner@001",
                     database="ipvacloud",
                     charset="utf8")
# 创建一个新游标来执行查询
curses = db.cursor()

siteId = "Ahczlcc_P00001"

# 查询SQL
selectSQL = """
    SELECT SiteId,SiteName from  site_all_info where SiteId ='%s'; 
""" % siteId
try:
    # 执行sql语句,也可执行数据库命令
    curses.execute(selectSQL)
    # 所有结果
    result = curses.fetchall()
    print(type(result))
    print(result)

except Exception as e:
    db.rollback()     # 回滚
    print("查询失败", e)
finally:
    curses.close()    # 关闭当前游标
    db.close()        # 关闭数据库连接

search result:

Additions, deletions, and changes require the operation of submitting transactions, and queries do not need to submit transactions. However, if you loop the query, you must submit the transaction, otherwise the results will be duplicated.

3.2 update


import pymysql
# 创建数据库连接对象
db = pymysql.connect(host="192.168.2.211",
                     user="root",
                     password="winner@001",
                     database="ipvacloud",
                     charset="utf8")
# 创建一个新游标来执行查询
curses = db.cursor()

siteId = "Ahczlcc_P00001"
siteName = "大中国安徽滁州乐彩城"

# 查询SQL
selectSQL = """
    update  site_all_info set sitename = '%s' where SiteId ='%s'; 
""" % (siteName, siteId)
try:
    # 执行sql语句,也可执行数据库命令
    curses.execute(selectSQL)
    # 增删改,必须执行事务
    db.commit()
    # 所有结果
    result = curses.fetchall()
    print(type(result))
    print(result)

except Exception as e:
    db.rollback()     # 回滚
    print("查询失败", e)
finally:
    curses.close()    # 关闭当前游标
    db.close()        # 关闭数据库连接

Query whether the update is successful

3.3 Batch update using loop


import pymysql

# 创建数据库连接对象
db = pymysql.connect(host="192.168.2.211",
                     user="root",
                     password="winner@001",
                     database="ipvacloud",
                     charset="utf8")
# 创建一个新游标来执行查询
curses = db.cursor()

siteId = "Ahczlcc_P00001"
siteName = "大中国安徽滁州乐彩城"

table_name = "site_all_info"
update_list = ['Ahczlcc_P00001S00004', 'Ahczlcc_P00001S00005']
update_condition_list = ['北餐饮门', '北大门']

for i in range(len(update_list)):
    # 查询SQL
    selectSQL = """
        update  %s set sitename = '%s' where SiteId ='%s'; 
    """ % (table_name, update_condition_list[i], update_list[i])
    print(table_name, update_condition_list[i], update_list[i])

    try:
        # 执行sql语句
        curses.execute(selectSQL)
        # 执行事务
        db.commit()
    except Exception as e:
        db.rollback()
        print(e)
curses.close()
db.close()

Comparison of execution results:


Learning record of Python series articles: 

Windows environment installation and configuration of Python series

Variables and operators of Python series

Judgment and cycle of Python series - Blog - CSDN Blog

Python series of strings and lists - blog driving tractor home - CSDN blog

File Operations and Functions of the Python Series

Detailed explanation of the standard library OS of Python series modules - Programmer Sought

Detailed explanation of the standard library re of Python series modules - Programmer Sought

Detailed explanation of the standard library json of Python series modules - Programmer Sought

Detailed explanation of the standard library shutil of Python series modules - Programmer Sought


reference:

python - detailed explanation of database operation PyMysql - Programmer Sought

Guess you like

Origin blog.csdn.net/qq_35995514/article/details/130984339