python MysqlDb模块安装及其使用详解
作者:此处无声胜有声 发布时间:2024-01-15 15:21:44
标签:python,MysqlDb模块
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
0
投稿
猜你喜欢
- 本文实例讲述了python分支、循环简单用法。分享给大家供大家参考,具体如下:讲程序设计,不得不讲到顺序、分支、循环。顺序就是从上到下运行代
- 1 The syntax of the SQL statement is verified.SQL的语法检查2 The data dicti
- 直接赋值:其实就是对象的引用(别名)。浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。深拷贝(deepcopy): copy 模
- 这篇文档所给出的编码约定适用于在主要的Python发布版本中组成标准库的Python 代码,请查阅相关的关
- 实现代码# -*- coding: cp936 -*-import re s1 = 'adkkdk's2 = 'ab
- 时间object转换datetime实例首先说一下:1/17/07 has the format “%m/%d/%y&a
- 一 NULL 为什么这么经常用(1) java的nullnull是一个让人头疼的问题,比如java中的NullPointerExceptio
- 顾名思义, 条件查询就是使用where字句 , 将满足条件的数据筛选出来语法 :select < 结果 > from <
- lambda/filter/map/reduce这几个函数面试中很肯定会用到,本篇主要介绍这几个函数的用法。1 lambda匿名函数,用法如
- gzip文件读写的时候需要用到Python的gzip模块。具体使用如下:# -*- coding: utf-8 -*-import gzip
- 前言又到了每日分享Python小技巧的时候了,今天给大家分享的是Python中两种常见的数据类型合并方法。1 合并字典在某些场景下,我们需要
- 通过优化CSS代码,减小对系统资源的占用。自己整理出几个能减少系统资源占用的CSS写法,要优化网站的页面加载速度,这些注意点不能忽视!一、尽
- 一. 这里第一步骤找到控制面板,点击卸载mysql。(1.)***请仔细按照步骤操作,mysql的卸载非常麻烦,少一个步骤都可能不成功。(2
- SQL Server判断语句(IF ELSE/CASE WHEN )执行顺序是 – 从上至下 – 从左至右 --,所当上一个条件满足时(无论
- 本文详细介绍了网站的反爬虫策略,在这里把我写爬虫以来遇到的各种反爬虫策略和应对的方法总结一下。从功能上来讲,爬虫一般分为数据采集,处理,储存
- 在这篇文章中,将向您展示如何使用Python链接目前主流的MongoDB(V3.4.0)数据库,主要使用PyMongo(v3.4.0)和Mo
- 官网下载就好, https://www.python.org/downloads/release/python-352/用installer
- '定义变量 Dim cn,rs,Sql Sql = "sel
- 类似Java打包操作,若不想让人看到Python程序内部逻辑,也可将其转换为exe可执行文件首先自己写一个Python程序,如下:print
- 本文实例讲述了Python运维自动化之nginx配置文件对比操作。分享给大家供大家参考,具体如下:文件差异对比diff.py#!/usr/b