python MysqlDb模块安装及其使用详解


Posted in Python onFebruary 23, 2018

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 MysqlDb模块安装及其使用详解

将其拷贝到Python安装目录下的Scripts目录下,在文件位置打开cmd,执行pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl

验证,python(command line)输入import MySQLdb,没报错,说明安装成功。

python 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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python字典操作简明总结
Apr 13 Python
在Django框架中运行Python应用全攻略
Jul 17 Python
Python+Selenium自动化实现分页(pagination)处理
Mar 31 Python
Python IDLE入门简介
Dec 08 Python
Python 实现两个列表里元素对应相乘的方法
Nov 14 Python
Python使用Selenium爬取淘宝异步加载的数据方法
Dec 17 Python
解决pycharm下os.system执行命令返回有中文乱码的问题
Jul 07 Python
Python面向对象封装操作案例详解
Dec 31 Python
Tensorflow安装问题: Could not find a version that satisfies the requirement tensorflow
Apr 20 Python
Python为何不支持switch语句原理详解
Oct 21 Python
举例讲解Python装饰器
Dec 24 Python
使用Django的JsonResponse返回数据的实现
Jan 15 Python
Python实现k-means算法
Feb 23 #Python
python语言中with as的用法使用详解
Feb 23 #Python
python实现定时自动备份文件到其他主机的实例代码
Feb 23 #Python
Python机器学习算法之k均值聚类(k-means)
Feb 23 #Python
python3调用R的示例代码
Feb 23 #Python
python中kmeans聚类实现代码
Feb 23 #Python
python实现SOM算法
Feb 23 #Python
You might like
模仿OSO的论坛(三)
2006/10/09 PHP
php你的验证码安全码?
2007/01/02 PHP
表格展示无限级分类(PHP版)
2012/08/21 PHP
php批量上传的实现代码
2013/06/09 PHP
PHP中4个加速、缓存扩展的区别和选用建议
2014/03/12 PHP
如何阻止网站被恶意反向代理访问(防网站镜像)
2014/03/18 PHP
ThinkPHP学习笔记(一)ThinkPHP部署
2014/06/22 PHP
php创建、获取cookie及基础要点分析
2015/01/26 PHP
PHP实现的curl批量请求操作示例
2018/06/06 PHP
php使用pecl方式安装扩展操作示例
2019/08/12 PHP
设定php简写功能的方法
2019/11/28 PHP
记录几个javascript有关的小细节
2007/04/02 Javascript
javascript 面向对象编程基础 多态
2009/08/21 Javascript
JavaScript 面向对象编程(2) 定义类
2010/05/18 Javascript
一次$.getJSON不执行的简单记录
2016/07/19 Javascript
浅谈jQuery中事情的动态绑定
2017/02/12 Javascript
详谈for循环里面的break和continue语句
2017/07/20 Javascript
vue 路由页面之间实现用手指进行滑动的方法
2018/02/23 Javascript
React diff算法的实现示例
2018/04/20 Javascript
vue弹窗插件实战代码
2018/09/08 Javascript
Vue实现搜索结果高亮显示关键字
2019/05/28 Javascript
JavaScript this使用方法图解
2020/02/04 Javascript
浅谈Vue 函数式组件的使用技巧
2020/06/16 Javascript
python使用自定义user-agent抓取网页的方法
2015/04/15 Python
Python操作串口的方法
2015/06/17 Python
Python DataFrame设置/更改列表字段/元素类型的方法
2018/06/09 Python
在Python中os.fork()产生子进程的例子
2019/08/08 Python
Pandas的数据过滤实现
2021/01/15 Python
西班牙美妆电商:Perfume’s Club(有中文站)
2018/08/08 全球购物
台湾专柜女包:KINAZ
2019/12/26 全球购物
美国鲜花递送:UrbanStems
2021/01/04 全球购物
药剂专业个人求职信范文
2014/04/29 职场文书
个人自荐材料
2014/05/23 职场文书
公司市场专员岗位职责
2014/06/29 职场文书
Python中的np.argmin()和np.argmax()函数用法
2021/06/02 Python
MySQL的索引你了解吗
2022/03/13 MySQL