[PYTHON]Python Coding - Connect to Mysql

标签: python mysql

偷懒了,今天学习怎么使用mysql-python来连接到数据库,然后把上次写的系统信息脚本中的内容写入到mysql数据库指定表中。

1. 安装mysql-python

pip install mysql-python

2. 连接到MySQL数据库,并写入数据到mysql数据库中

代码:



import mysql.connector, psutil, datetime,socket

###CPU INFO
def fun_cpuinfo():
    cpulog = str(psutil.cpu_count())
    cpuphy = str(psutil.cpu_count(logical=False))
    cpuinfo = ("物理个数:" + cpuphy + " 逻辑个数:" + cpulog)
    return cpuinfo


###MEMORY INFO
def fun_meminfo():
    mem = psutil.virtual_memory()
    memtotal = mem.total / 1024 / 1024
    memused = mem.used / 1024 / 1024
    memperc = str(memused / memtotal * 100)
    meminfo = ("总内存:" + str(memtotal) + " 已使用:" + str(memused) + " 百分比:" + memperc[0:6])
    return meminfo


###DISK INFO
def fun_diskinfo():
    diskpoint = psutil.disk_partitions()
    diskcount = psutil.disk_usage("/")
    return diskpoint, diskcount


###NETWORK INFO
def fun_ifinfo():
    ifinfo = psutil.net_if_addrs()
    return ifinfo


###BOOT TIME INFO
def fun_boottime():
    boottime = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    return boottime


###USER INFO
def fun_userinfo():
    userinfo = psutil.users()
    return userinfo


python_mysql = {
    'host': '',
    'user': 'zhangky',
    'password': '',
    'port': 3306,
    'database': 'python',
    'charset': 'utf8'
}


def insert_command(insert_cmd, param):
    """
    :param insert_cmd:
    :param param:
    """
    try:
        conn = mysql.connector.connect(**python_mysql)
    except mysql.connector.Error as error:
        print('连接失败!', format(error))
    cursor = conn.cursor()
    try:
        cursor.execute(insert_cmd,param)
        conn.commit()                           ###知识点如果数据库引擎为InnoDB时,必须使用commit
    except mysql.connector.Error as error:
        print('连接失败!', format(error))
    finally:
        cursor.close()
        conn.close()

hostname = socket.gethostname()
userstr = str(fun_userinfo())
cpustr = str(fun_cpuinfo())
memstr = str(fun_meminfo())
diskstr = str(fun_diskinfo())
ifstr = str(fun_ifinfo())
bootstr = str(fun_boottime())

insert_cmd = "insert into systeminfo(hostname, loginuser, cpus, meminfo, diskinfo, networkinfo, boottime) values (%s, %s, %s, %s, %s, %s, %s);"
param = (hostname, userstr, cpustr, memstr, diskstr, ifstr, bootstr)
insert_command(insert_cmd=insert_cmd, param=param)


有点难,完全没有编程思想,不知道应该怎么去实现。。。不说了先睡觉

版权所有:《Hoiwan's 》 => 《[PYTHON]Python Coding - Connect to Mysql
本文地址:http://ihoiwan.com/?post=49
除非注明,文章均为 《Hoiwan's 》 原创,欢迎转载!转载请注明本文地址,谢谢。

发表评论: