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

yipeiwu_com6年前Python基础

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python遍历字典方式就实例详解

这篇文章主要介绍了Python遍历字典方式就实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 “ 记录遍历字典的几种方式”...

python应用程序在windows下不出现cmd窗口的办法

python写的GTK程序,会有这样一个怪现象,本来在cmd下用 python xxx.py 启动,还好好的,但是用py2exe编译以后,再用subprocess调用命令行程序的时候,就...

python验证身份证信息实例代码

python验证身份证信息实例代码

identity-card 验证身份证号码的正确性,不能仅仅通过正则表达式来验证,我们都知道我国的身份证一共是18位,由十七位数字本体码和一位校验码组成。 其排列顺序从左至右依次为:六位...

Python实现的生成自我描述脚本分享(很有意思的程序)

自我描述的语句指这样一种语句:它的内容就是对它本身的描述。(废话……)比如下面这句句子: 复制代码 代码如下: 这是一段自我描述的语句,除了标点符号外,它共包含125个字符,其中33个“...

python2和python3实现在图片上加汉字的方法

python2和python3实现在图片上加汉字的方法

python2和python3实现在图片上加汉字,最主要的区别还是内部编码方式不一样导致的,在代码上表现为些许的差别。理解了内部编码原理也就不会遇到这些问题了,以下代码是在WIN10系统...