python2操作mysql数据库_例程

首先MySQLdb库是一个第三方库,需要使用pip安装相关库

pip install mysql-python

安装成功之后进入例程

例程的主要功能是

  1. 连接mysql数据库
  2. 执行相关mysql语句
  3. 关闭连接
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

#数据库连接信息
mysqlURL = "10.240.184.74"
userName = "mawenxuan"
password = "Winxuan666"
sqlName = "h67_codecoverage"

# 函数功能:连接mysql数据库
def connectMysql():
    db = MySQLdb.connect(
        mysqlURL, 
        userName, 
        password, 
        sqlName, 
        charset='utf8' 
        )
    return db

# 函数功能:断开mysql数据库
def disconnectMysql(db):
    db.close()

# 函数功能:获取游标
def getCursor(db):
    return db.cursor()

# 函数功能:
def demo():
    # 连接数据库
    db = connectMysql()
    cursor = getCursor(db)

    # 执行insert sql语句
    sql = "insert into xxxxxxxxxxxxxxx"
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
        print "insert success"
    except:
        # Rollback in case there is any error
        db.rollback()
        print "error"

    # 执行select sql语句(查询得到的数据就一个)
    sql = "select xxxxxxxxxx"
    try:
        cursor.execute(sql)
        data = cursor.fetchone()
        print data
    except:
        print "Error: unable to fecth data"

    # 执行select sql语句(查询得到的数据为多个)
    lsFile = list()
    sql = "SELECT xxxxxxxxxxxxxxxxxxx"
    try:
        cursor.execute(sql)
        data = cursor.fetchone()
        while data != None:
            lsFile.append(os.path.join(data[0], data[1]))
            data = cursor.fetchone()
    except:
        print "Error: unable to fecth data"

    # 断开数据库连接
    disconnectMysql(db)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值