Python connects Mysql to add, delete, modify and check

Python connect to Mysql

1. Install the corresponding library

Use Python to connect to Mysql database, you need to install the corresponding library

Run cmd as an administrator and enter the command

pip install mysql-connector

After the installation is complete, create,
test.py
write, and
import mysql.connector
save and run. It is
python test.py
used to test whether the module library is installed. If no error is reported, the installation is complete.

2. Perform a connection test

Prepare the connectTest.pyfile
File content:

import mysql.connector


connect = mysql.connector.connect(
    host="127.0.0.1",       # 数据库主机地址
    user="root",            # 数据库用户名
    passwd="root",          # 数据库密码
    database="mysql"  # 要连接的数据库
)
#关闭连接
connect.close()

python connectTest.pyIf there is no error message in the running file, the connection is successful. If an error message is displayed, the Insert picture description here
connection has failed. Please check whether the account, password, and database are correct, and check whether the database is powered on.

3. Execute the sql command

3.1 Create a table

import mysql.connector


connect = mysql.connector.connect(
    host="127.0.0.1",       # 数据库主机地址
    user="root",            # 数据库用户名
    passwd="root",          # 数据库密码
    database="test"  		# 要连接的数据库
)

#数据库建表指令
sql = """CREATE TABLE `test`.`testtable`  (
        `id` int NOT NULL,
        `name` varchar(255) NULL,
        `age` int NULL,
        `address` varchar(255) NULL,
        PRIMARY KEY (`id`)
        );"""
#获取数据库操作游标
myCursor=connect.cursor()
#执行sql语句
myCursor.execute(sql)
#提交给数据库执行命令
connect.commit()

connect.close()

After execution, a table named testtabe will be created
Insert picture description here

3.2 Insert data

Insert picture description here

import mysql.connector


connect = mysql.connector.connect(
    host="127.0.0.1",       # 数据库主机地址
    user="root",            # 数据库用户名
    passwd="root",          # 数据库密码
    database="test"         # 要连接的数据库
)

# 数据库插入指令,待定字符无论是数值还是文字,都需要用%s
sql = "INSERT INTO `test`.`testtable`(`id`, `name`, `age`, `address`) VALUES (%s,%s,%s,%s)"

var = (1, 'windSnowLi', 20, '中国')


# 获取数据库操作游标
myCursor = connect.cursor()
try:
    # 执行sql语句
    myCursor.execute(sql, var)
    # 提交给数据库执行命令
    connect.commit()
except :
    #回滚,以防出现错误
    connect.rollback()

connect.close()

Then check the database
Insert picture description here

3.3 query statement

import mysql.connector


connect = mysql.connector.connect(
    host="127.0.0.1",       # 数据库主机地址
    user="root",            # 数据库用户名
    passwd="root",          # 数据库密码
    database="test"         # 要连接的数据库
)

# 数据库查询指令
sql = "select * from testtable"


# 获取数据库操作游标
myCursor = connect.cursor()
try:
    # 执行sql语句
    myCursor.execute(sql)
    results = myCursor.fetchall()
    print(results)
except :
   print("查询失败")

connect.close()

Insert picture description here

3.4 Update data

import mysql.connector


connect = mysql.connector.connect(
    host="127.0.0.1",       # 数据库主机地址
    user="root",            # 数据库用户名
    passwd="root",          # 数据库密码
    database="test"         # 要连接的数据库
)

# 数据库更新指令
sql = "UPDATE `test`.`testtable` SET `id` = 2, `name` = 'mirror', `age` = 19, `address` = '祖国' WHERE `id` = 1"

# 获取数据库操作游标
myCursor = connect.cursor()
try:
    # 执行sql语句
    myCursor.execute(sql)
    # 提交给数据库执行命令
    connect.commit()
except :
    #回滚,以防出现错误
    connect.rollback()

connect.close()

Insert picture description here

3.5 Delete data

import mysql.connector


connect = mysql.connector.connect(
    host="127.0.0.1",       # 数据库主机地址
    user="root",            # 数据库用户名
    passwd="root",          # 数据库密码
    database="test"         # 要连接的数据库
)

# 数据库删除指令
sql = "DELETE FROM `test`.`testtable` WHERE `id` = 1"

# 获取数据库操作游标
myCursor = connect.cursor()
try:
    # 执行sql语句
    myCursor.execute(sql)
    # 提交给数据库执行命令
    connect.commit()
except :
    #回滚,以防出现错误
    connect.rollback()

connect.close()

Insert picture description here

4. Description

If there are undetermined characters in the sql statement, you can pass

sql = "INSERT INTO `test`.`testtable`(`id`, `name`, `age`, `address`) VALUES (%s,%s,%s,%s)"

var = (1, 'windSnowLi', 20, '中国')

This way of splicing, but
myCursor.execute(sql, var)the parameters need to be synchronously passed in during execution

Guess you like

Origin blog.csdn.net/qq_44575789/article/details/107597038