Python 操作 MySQL 数据库

1.安装驱动

pip install mysql-connector-python

 

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
import mysql.connector
from mysql.connector import errorcode
 
# cnx = mysql.connector.connect(user='scott', password='password',
#                               host='127.0.0.1',
#                               database='employees')
# cnx.close()
try:
    cnx = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='bugfree')
    cursor = cnx.cursor()
    query = "select * from bf_bug_info"
    cursor.execute(query)
 
    #单条取值方式
    while (True):
        data = cursor.fetchone()
        if data == None:
            break
        print(data)
 
    #全部取值方式
    # datas = cursor.fetchall()
    # for data in datas:
    #     print(data)
    # print(datas)
 
 
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)
finally :
    cursor.close()
    cnx.close()
#官方示例
# query = ("SELECT first_name, last_name, hire_date FROM employees "
#          "WHERE hire_date BETWEEN %s AND %s")
#
# hire_start = datetime.date(1999, 1, 1)
# hire_end = datetime.date(1999, 12, 31)
#
# cursor.execute(query, (hire_start, hire_end))
#
# for (first_name, last_name, hire_date) in cursor:
#   print("{}, {} was hired on {:%d %b %Y}".format(
#     last_name, first_name, hire_date))
#
# cursor.close()
# cnx.close()

  

posted @   等一念  阅读(192)  评论(0编辑  收藏  举报
编辑推荐:
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
阅读排行:
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
点击右上角即可分享
微信分享提示