Python uses PyMysql to connect to MySQL to implement additions, deletions, and changes

1. Install PyMysql:

1. Method 1: Use the command line

Open cmd and enter the following code:

pip install PyMysql

2. Method 2: Through the PyCharm compiler

If you are using the development tool: pycharm, you can directly enter settinginto the Project interperter to download, click the plus sign to download the corresponding dependency package l
Insert picture description here

Steps to operate MySQL database

1. Use import to import the corresponding class

import pymysql

Tip: You can use the following methods to eliminate the warning in the Pycharm compiler (just import, you need to wrap)

import warnings
warnings.filterwarnings("ignore")

2. Get a connection to the database

db = pymysql.connect("主机IP地址", "用户名", "密码", "需要连接的数据库名")

3. Create a cursor object

cursor = db.cursor()

4. Execute SQL statement

 cursor.execute("SQL语句")

5. Close the database connection

db.close()

Three, case

Several functions:

function Explanation
fetchone() Return a query object
fetchall() Return all rows
rowcount() Return the number of rows affected by execute(): operation

1. Query a single piece of data

def findAll():
    # 1.打开数据库连接
    db = pymysql.connect("localhost", "root", "root", "student")
    # 2.创建游标对象
    cursor = db.cursor()
    # 执行SQL查询
    cursor.execute("select * from user")
    # 获得单条数据
    dataOne = cursor.fetchone()
    # 关闭数据库连接
    db.close()

2. Query multiple data

def findAll():
    # 1.打开数据库连接
    db = pymysql.connect("localhost", "root", "root", "student")
    # 2.创建游标对象
    cursor = db.cursor()
    # 查询所有的记录
    cursor.execute("select * from user")
    dataAll = cursor.fetchall()
    print(dataAll)
    # 关闭数据库连接
    db.close()

3. Create a database table

Note: Before creating, determine whether the table name is known to exist, if it exists, an exception will be reported

def createTable():
    db = pymysql.connect("localhost", "root", "root", "student")
    cursor = db.cursor()
    # 创建表SQL
    sql = """create table student(sno varchar(12),name varchar(12))"""
    # 执行创建表操作
    cursor.execute(sql)
    db.close()

4. Insert record

def insert():
    print("执行:insert...")
    db = pymysql.connect("localhost", "root", "root", "student")
    cursor = db.cursor()
    sql = """insert into student(sno,name)values('2018010211','张小飞')"""
    try:
        # 执行操作
        cursor.execute(sql)
        # 提交事务
        db.commit()
        # 换回影响条数
        count = cursor.rowcount
        print(count)
        print("提交成功")
    except:
        # 发生错误时回滚
        db.rollback()
        print("出现异常...")
    db.close()

Tip: The rest of the operations only need to modify the SQL statement.

Guess you like

Origin blog.csdn.net/qq_43073558/article/details/107143071