《跟着小吴哥学python》之 13 Python访问mysql数据库

本文详细介绍如何在Python环境中安装MySQL驱动,实现数据库的连接、数据的增删改查等基本操作,包括在不同操作系统下的安装指导及常用数据库操作代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、安装mysql-python驱动模块

1、pip install mysql-python
2、如果你使用的默认安装的python也可以使用 yum 安装 MySQL-python
yum install MySQL-python
如果你要在linux 下开发python程序要安装一下开发包。否则可以忽略。
yum install python-devel mysql-devel zlib-devel openssl-devel
3、windows下直接去pypi官网下载exe文件即可:

目前官网只有32位的mysql-python.exe驱动,地址:https://pypi.org/project/MySQL-python/,中下载MySQL-python-1.2.5.win32-py2.7.exe 。

http://www.codegood.com/archives/129      此地址 中32位和64位驱动均可下载。

2、初始化连接

模块引入之后我们就需要和数据库进行连接了,实例代码如下: 
 

import MySQLdb
db = MySQLdb.connect(“127.0.0.1”,”root","123456","myciti" )
db = MySQLdb.connect(host="192.168.1.155", user="root", passwd="haha", db="test",charset="utf8")

数据库连接对事务操作的方法:commit() 提交    rollback() 回滚

详细参数:

host,连接的数据库服务器主机名,默认为本地主机(localhost)。 
user,连接数据库的用户名,默认为当前用户。 
passwd,连接密码,没有默认值。 
db,连接的数据库名,没有默认值。 
charset,连接字符集
conv,将文字映射到Python类型的字典。默认为MySQLdb.converters.conversions 
cursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor。 
compress,启用协议压缩功能。 
named_pipe,在windows中,与一个命名管道相连接。 
init_command,一旦连接建立,就为数据库服务器指定一条语句来运行。 
read_default_file,使用指定的MySQL配置文件。 
read_default_group,读取的默认组。 
unix_socket,在unix中,连接使用的套接字,默认使用TCP。 
port,指定数据库服务器的连接端口,默认是3306 

3、操作实例

#新增数据:  
cursorAdd = dbAdd.cursor() 
sql = "INSERT into t_user (name,address,phone) VALUES('%s','%s','%s');" % ("you","BJ","1222222")
print(cursorAdd.execute(sql))
dbAdd.commit()
dbAdd.close()

#删除数据:
cursorDel = dbDel.cursor()
sql = "delete from  t_user where id=10;"
cursorDel.execute(sql)
dbDel.commit()
dbDel.close()

#修改数据:
cursorUpdate = dbUpdate.cursor()
sql = "update t_user set address='%s' where address='BJ';"%"BJJ"
cursorUpdate.execute(sql)
#dbUpdate.rollback()
dbUpdate.commit()
dbUpdate.close
cursor.execute(sql):返回执行后影响的行数。

#查询结果集:cursorSearch = dbSearch.cursor()
sql = "select * from t_user;"
cursorSearch.execute(sql)
data = cursorSearch.fetchall()
#data = cursorSearch.fetchone()
print cursorSearch.rowcount
for d in data:
	print d
	print d[2].encode("utf-8")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值