原生python操作mysql

点击查看代码
# -*- coding: utf-8 -*-
import subprocess

class MySQL(object):
    def __init__(self):
        self.sql = None
        self.re  = None
        self.out = None
        print("程序初始化.....")
        self.connection()

    def connection(self):
        print("请输入数据库连接信息.")
        user = input("登录账号: ")
        pwd  = input("登录密码: ")
        cmd = ['mysql', f'-u{user}', f'-p{pwd}']
        self.re = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
        print("连接成功!")
        self.query()

    def query(self):
        self.sql = input("mysql> ")
        self.re.stdin.write(self.sql)
        self.out = self.re.communicate()[0]
        print(self.out)

if __name__ == '__main__':
    MySQL()
posted @ 2022-03-01 18:14  寻月隐君  阅读(30)  评论(0编辑  收藏  举报