python mysql ping_Python 连接 MySQL

本文介绍了两种Python连接MySQL的方法:1) 普通MySQL连接,使用MySQLdb模块;2) 使用连接池PooledDB进行连接,详细阐述了连接池的配置和使用。示例代码展示了如何执行SQL查询、插入操作,并处理异常。
摘要由CSDN通过智能技术生成

一、普通 MySQL 连接方法

使用模块 MySQLdb 普通方式连接。

#!/usr/bin/env python

# _*_ coding:utf-8 _*_

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='test')

cursor = conn.cursor()

sql_1 = "select * from user where id = %s;" % (5,)

sql_2 = "select * from user \

where id = %s;" % (5,)

sql_3 = """

insert into user(username, password)

values("yuchaoshui", "123");

"""

try:

print cursor.execute(sql_1)

print cursor.fetchall()

print cursor.execute(sql_2)

print cursor.fetchall()

print cursor.execute(sql_3)

conn.commit()

except Exception as e:

print(e)

conn.rollback()

cursor.close()

conn.close()

execute() 返回结果表示影响的行数。cursor.fetchone() 取回一条结果。sql_1 直接一行写完,sql_2 换行写完, sql_3 多行写。 查询时不需要 commit() 操作,插入、更新、删除时需要 commit() 提交。

二、使用连接池连接MySQL

#!/usr/bin/env python

# _*_ coding:utf-8 _*_

import MySQLdb

from DBUtils.PooledDB import PooledDB

pool = PooledDB(MySQLdb, 5, host='127.0.0.1', port=3306, user='root', passwd='123', db=

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值