python MysqlDb模块安装及其使用详解
作者:此处无声胜有声 时间:2024-01-15 15:21:44
python调用mysql数据库通常通过mysqldb模块,简单说下如何调用
1.安装驱动
目前有两个MySQL的驱动,我们可以选择其中一个进行安装:
1. MySQL-python:是封装了MySQL C驱动的Python驱动;
2.mysql-connector-python:是MySQL官方的纯Python驱动。
这里使用MySQL-python驱动,即MySQLdb模块。
命令行安装
pip install python-mysql
或者在pycharm包中安装
源码安装方式
访问: http://www.lfd.uci.edu/~gohlke/pythonlibs/,下载MySQL_python-1.2.5-cp27-none-win_amd64.whl
将其拷贝到Python安装目录下的Scripts目录下,在文件位置打开cmd,执行pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl
验证,python(command line)输入import MySQLdb,没报错,说明安装成功。
测试连接:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 连接数据库 连接地址 账号 密码 数据库 数据库编码
db = MySQLdb.connect("localhost", "root", "123456", "test" , charset="utf8")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据库。
data = cursor.fetchone()
print "Database version : %s " % data
# 关闭数据库连接
db.close()
示例1:
#!/usr/bin/python
# coding=utf-8
import MySQLdb
import os, sys
import json
class MysqlDb(object):
def __init__(self):
self.host = "127.0.0.1"
@staticmethod
def get_connect():
db = MySQLdb.connect(self.host , "mail_report", "mail_report", "mailawst", charset="utf8")
return db
def get_mysql_info(self,start_time,end_time):
tmp = []
db = self.get_connect()
sql = 'select send_time,mail_id,mail_addr,server_domain,server_ip,mail_status from real_mail_log where send_time > "%s" and send_time < "%s" limit 10;' % (start_time,end_time)
cursor = db.cursor()
cursor.execute(sql)
values = cursor.fetchall()
for i in values:
data = {}
data["send_time"] = str(i[0])
data["mail_id"] = str(i[1])
data["mail_addr"]= str(i[2])
data["server_domain"] = str(i[3])
data["server_ip"] = str(i[4])
data["mail_status"]= str(i[5].encode('utf8'))
tmp.append(data)
data = json.dumps(tmp,ensure_ascii=False)
db.close()
return data
def main():
u = MysqlDb()
print u.get_mysql_info('2017-05-01 00:00:02','2017-05-01 00:50:03')
if __name__ == '__main__':
main()
示例2:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "123456", "test")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL插入语句
ins_sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('yu', 'jie', 20, 'M', 8000)"""
ins_sql1 = 'insert into employee(first_name, last_name, age, sex, income) values (%s, %s, %s, %s, %s)'
# SQL查询语句
sel_sql = 'select * from employee where first_name = %s'
# SQL更新语句
upd_sql = 'update employee set age = %s where sex = %s'
# SQL删除语句
del_sql = 'delete from employee where first_name = %s'
try:
# 执行sql语句
# insert
cursor.execute(ins_sql)
cursor.execute(ins_sql1, ('xu', 'f', 20, 'M', 8000))
# select
cursor.execute(sel_sql, ('yu',))
values = cursor.fetchall()
print values
# update
cursor.execute(upd_sql, (24, 'M',))
# delete
cursor.execute(del_sql, ('xu',))
# 提交到数据库执行
db.commit()
except:
# 发生错误时回滚
db.rollback()
# 关闭数据库连接
db.close()
来源:http://blog.csdn.net/qq_24074149/article/details/79247188
标签:python,MysqlDb模块
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP的mysqli_stat()函数讲解
2023-06-12 08:11:33
![](https://img.aspxhome.com/file/2023/5/55455_0s.png)
Nodejs 和Session 原理及实战技巧小结
2024-05-13 10:06:08
![](https://img.aspxhome.com/file/2023/7/125837_0s.png)
Python基于mysql实现学生管理系统
2024-01-24 05:57:47
Linux添加Python path方法及修改环境变量的三种方法
2021-03-26 12:22:45
Python Opencv任意形状目标检测并绘制框图
2023-06-06 19:03:43
![](https://img.aspxhome.com/file/2023/7/92417_0s.jpg)
LotusPhp笔记之:基于ObjectUtil组件的使用分析
2023-11-19 09:18:32
pytorch中的squeeze函数、cat函数使用
2022-03-27 14:32:24
python机器学习之神经网络(二)
2021-12-21 08:41:54
![](https://img.aspxhome.com/file/2023/4/130974_0s.jpg)
mysql按照自定义(指定顺序)排序的方法实例
2024-01-14 12:33:46
![](https://img.aspxhome.com/file/2023/1/122891_0s.jpg)
js实现黑色简易的滑动门网页tab选项卡效果
2024-04-23 09:05:53
![](https://img.aspxhome.com/file/2023/9/135939_0s.jpg)
TensorFlow安装及jupyter notebook配置方法
2022-09-11 01:05:23
打包发布Python模块的方法详解
2021-04-03 06:10:56
golang中的并发和并行
2024-04-26 17:15:11
使用navicat将csv文件导入mysql
2024-01-17 07:06:38
![](https://img.aspxhome.com/file/2023/2/65302_0s.png)
PHP简单实现正则匹配省市区的方法
2023-11-14 22:24:09
Python中使用Frozenset对象的案例详解
2023-09-27 09:36:32
10个php函数实用却不常见
2023-11-05 01:40:43
解密SQL Server数据库系统的编译
2009-03-16 17:33:00
网页绿色系配色应用实例
2008-08-26 11:51:00
![](https://img.aspxhome.com/file/UploadPic/20088/26/2008826115322660s.gif)
Python压缩解压缩zip文件及破解zip文件密码的方法
2023-04-20 10:30:30
![](https://img.aspxhome.com/file/2023/2/65932_0s.jpg)