直接看代码吧:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# ########################################
# import

# -- os
import sys

# -- Command Options
#import getopt
import argparse

# -- MySQL
import pymysql

# ########################################
# variable

# -- Meta:关于本脚本的调用与控制

# 该脚本将以什么方式运行
# 对数据的增加,ADD
# 对数据的删除,DELETE
# 对数据的修改,MODIFY
meta_python_options_OpsMode=""

# -- MySQL
mysql_host="***你不需要知道的主机地址***"
mysql_user="***你不需要知道的用户名***"
mysql_passwd="***你不需要知道的口令***"
mysql_database="***你不需要知道的数据库名***"

# ########################################
# function

# init
def __init__(self):
    pass

# -- Show message out

# 直接输出信息
# 目标:统一输出
def show_message(message_string):

    # do - display
    print("================")
    print(message_string)
    print("")

# -- MySQL

# ===================================
# 数据库:连接阶段

# 数据库:连接方法
# 根据变量区域的变量,返回一个数据库的连接对象
def mysql_return_connect():

    # variable
    db = pymysql.connect(mysql_host,mysql_user,mysql_passwd,mysql_database)

    # return
    return db

# 根据数据库连接对象,返回一个数据库游标对象
def mysql_return_cursor(db_connect):

    # variable
    cursor = db_connect.cursor(pymysql.cursors.DictCursor)

    # return
    return cursor

# ===================================
# 数据库:使用阶段

# ---------------
# 查
# 查询方法

# 最简单的查询,并返回MySQL的查询结果
# 1. 执行SQL
# 2. 选择结果集的返回模式
#   all
#   one
#   many,3 - 返回三行

def mysql_do_select(db_connect,sql_command_string,result_set_mode,result_set_lines=0):

    # variable
    db_cursor=mysql_return_cursor(db_connect)

    # 结果集
    result_set=""

    # do
    try:
        # 执行SQL的命令语句
        db_cursor.execute(sql_command_string)

        # 获取SQL的执行结果
        #result_set=db_cursor.fetchall()

        if (result_set_mode=="all"):
            result_set = db_cursor.fetchall()
        elif (result_set_mode=="one"):
            result_set = db_cursor.fetchone()
        elif (result_set_mode=="many"):
            result_set = db_cursor.fetchmany(result_set_lines)
        else:
            show_message("需要指定结果集的模式")

    except:
        # variable
        error_info = sys.exc_info()

        # display
        show_message("Error: unable to fetch data from MySQL.")
        print( error_info[0], ":", error_info[1])

    finally:
        # 清理数据库连接资源
        mysql_do_cleanup(db_connect)

    # display
    #print(result_set)

    # return
    return result_set

# 判断SQL的查询是否有结果

def mysql_do_select_isNull(mysql_result_set):

    # variable
    result=False

    # do
    if mysql_result_set:
        result=True
    else:
        result = False

    # return
    return result

# ---------------
# 删
# ---------------
# 改
# ---------------
# 增

# 对数据库做增(Insert)删(Delete)改(Update)查操作
# 并返回是否执行成功
def mysql_do_IDU(db_connect,sql_command_string):

    # variable
    # -- return
    result=False
    # -- MySQL
    db_cursor=mysql_return_cursor(db_connect)

    # do
    try:
        # DB Execute SQL
        db_cursor.execute(sql_command_string)

        # DB Commit
        db_connect.commit()

        # change status
        result=True

    except:
        # variable
        error_info = sys.exc_info()

        # display
        show_message("Error: unable to execute SQL")
        print(error_info[0], ":", error_info[1])

        # MySQL - Roll back
        db_connect.rollback()

        # change status
        result = False

    finally:
        # 清理数据库连接资源
        mysql_do_cleanup(db_connect)

    # return
    return result

# ===================================
# 数据库:关闭阶段

# 数据库:关闭阶段 - 清理方法
# 传入,数据库连接对象
def mysql_do_cleanup(db_connect):

    # display
    #show_message("数据库 - 关闭阶段:清理")

    # do

    # 关闭数据库连接
    db_connect.close()


# ########################################
# do

# Print Hello world
#print("Hello world.")

# db - mysql

# 查询
#mysql_do_select(mysql_return_cursor(mysql_return_connect()),"select count(*) from person;")

#db = mysql_return_connect()
#cursor = mysql_return_cursor(db)
#print(mysql_do_select(cursor,"select name,email from person","one"))

#print(mysql_do_select(mysql_return_cursor(mysql_return_connect()),"select name,email from person","all"))

#print(mysql_do_select(mysql_return_cursor(mysql_return_connect()),"select name,email from person","many",2))

#result=mysql_do_select(mysql_return_cursor(mysql_return_connect()),"select name,email from person where name='adamhuan'","many",2)
#if result:
#    print("查得出内容")
#else:
#    print("查不出内容")

#result=mysql_do_select(mysql_return_cursor(mysql_return_connect()),"select name,email from person where name='adamhuan'","many",2)
#if mysql_do_select_isNull(result):
#    print("YES")
#else:
#    print("NO")

#result=mysql_do_select(mysql_return_connect(),"select name,email from person","many",1)
#done=mysql_do_select_isNull(result)
#show_message(result)
#show_message(done)

# 执行SQL

#result = mysql_do_IDU(mysql_return_connect(),"drop database abc;")
#show_message(result)

if __name__ == "__main__":

    # 命令行参数
    parser = argparse.ArgumentParser(description='How to use This Python Script')

    # -- options
    parser.add_argument('--OpsMode', type=str, default=None)

    # -- analyze
    args = parser.parse_args()

    # -- store to variable
    meta_python_options_OpsMode=args.OpsMode

    # display
    #print(meta_python_options_OpsMode)

# done

——————————————————————
Done。

1
说点什么

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

  Subscribe  
提醒
trackback

[…] Python:MySQL 操纵类 […]