python连接mysql

import pymysql

class c_mysql(object):

    def __init__(self, ip, port, user, password, databasename):
        self.ip = ip
        self.port = port
        self.user = user
        self.password = password
        self.databasename = databasename

    def connect_mysql(self):
        try:
            db = pymysql.connect(self.ip, self.user, self.password, self.databasename, self.port)
            return db
        except Exception as e:
            print(e)
    # 操作
    # def action_sql(self, db):
    #     cursor = db.cursor()
    #     sql ="insert into subiject (id,name,content,tuition) values (4,"d","ac","20");"
    #     cursor.execute(sql)
    #     db.commit()
    #     cursor.close()
    #     db.close()
    # 查看
    def b_sql(self,db):
        cursor =db.cursor()
        sql ="select * from subiject"
        cursor.execute(sql)
        res = cursor.fetchall()  # fetchall --> 展示全部    fatone --> 展示一条     fetchmany(n) --> 展示n        print((res))
        db.commit()
        cursor.close()
        db.close()


c =c_mysql("#mysql的ip", 3306, "#登录用户", "#密码", "#数据库名" )
db =c.connect_mysql()
# c.action_sql(db)
c.b_sql(db)
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » python连接mysql