Python pymysql操作MySQL详细

时间:2021-08-19 22:22:34

1、使用

1.1 简单使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import pymysql
 
# 创建连接
con = pymysql.connect(
                        host='localhost',
                        port=3306,
                        user='root',
                        password='123456',
                        database='test',
                        charset='utf8'
)
# 创建游标
cursor = con.cursor()
 
# 执行新增SQL,返回受影响行数
row1 = cursor.execute("insert into user (username, password) values ('username3','password3')")
print(row1)
 
# 执行更新SQL,返回受影响行数
row2 = cursor.execute("update user set password = '123456' where id > 2;")
# 执行查询SQL
res = cursor.execute("SELECT * FROM user;")
result = cursor.fetchall()
for info in result:
    print(info[0], info[1])
# 提交,不然无法保存新增或者更新的数据
con.commit()
# 关闭游标
cursor.close()
# 关闭连接
con.close()

注意:数据库表中存在中文时,创建连接需要指定charset='utf8',否则中文显示会乱码。 其中cursor.fetchall()是获取所有结果集,如果只有一条结果集,可以使用cursor.fetchone()

1.2 封装工具类

为了使用方便,可以直接封装成工具类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import pymysql
 
 
class MysqlHelper:
    def __init__(self, config):
        self.host = config["host"]
        self.port = config["port"]
        self.user = config["user"]
        self.password = config["password"]
        self.db = config["db"]
        self.charset = config["charset"]
        self.con = None
        self.cursor = None
 
    def create_con(self):
        """
        创建连接
        """
        try:
            self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
                                       database=self.db, charset='utf8')
            self.cursor = self.con.cursor()
            return True
        except Exception as e:
            print(e)
            return False
 
    #
    def close_con(self):
        """
        关闭链接
        """
        if self.cursor:
            self.cursor.close()
        if self.con:
            self.con.close()
 
    # sql执行
    def execute_sql(self, sql):
        """
        执行插入/更新/删除语句
        """
        try:
            self.create_con()
            print(sql)
            self.cursor.execute(sql)
            self.con.commit()
        except Exception as e:
            print(e)
        finally:
            self.close_con()
 
    def select(self, sql, *args):
        """
        执行查询语句
        """
        try:
            self.create_con()
            print(sql)
            self.cursor.execute(sql, args)
            res = self.cursor.fetchall()
            return res
        except Exception as e:
            print(e)
            return False
        finally:
            self.close_con()

使用工具类:

?
1
2
3
4
5
6
7
8
9
10
11
config = {
    "host": 'localhost',
    "port": 3306,
    "user": 'root',
    "password": '123456',
    "db": 'test',
    "charset": 'utf8'
}
db = MysqlHelper(config)
db.execute_sql("insert into user (username, password) values ('username4','password4')")
db.select("SELECT * FROM user;")

到此这篇关于Python pymysql操作MySQL详细的文章就介绍到这了,更多相关Python pymysql操作MySQL内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/7003200519103578126