python-mysqldemo

python连接MySQL数据库

'''
python连接mysqldemo

1.获取数据库
2.获取记录
3.增加记录
4.修改记录
5.删除记录
6............
'''

__author__ = 'xiaolong'
import pymysql

class MysqlDemo(object):
    # 设置数据库连接参数,默认编码类型为utf-8,参数为字符串
    def __init__(self,host,username,password,dbname):
        self.conn = pymysql.connect(host,username,password,dbname,charset='utf8')
        self.cursor = self.conn.cursor()

    # 更新数据
    def update(self,tablename,data,restrication_str):
        data_str = ''
        for item in data.items():
            data_str += '{}={},'.format(item[0],item[1])
        values = data_str[:-1]
        sql = 'update {} set {} where {}'.format(tablename,values,restrication_str)
        print(sql)
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return self.cursor.rowcount
        except Exception as e:
            print(e)
            self.conn.rollback()

        # 获取所有数据
    def get_all(self,sql):
        try:
            self.cursor.execute(sql)
            results = self.cursor.fetchall()
            print(results)
            return results
        except Exception as e:
            print(e)
            return False


    # 获取一条数据
    def get_one(self,sql):
        try:
            self.cursor.execute(sql)
            results = self.cursor.fetchone()
            print(results)
            return results
        except Exception as e:
            print(e)
            return False

    # 插入数据
    def insert(self,tablename,data):
        if len(data.keys()) == 1:
            sql = 'insert into {}{} values'.format(tablename,data.keys[0]).replace("'",'') + '{}'.format(data.values()[0])

        else:
            sql = 'insert into {}{} values'.format(tablename,tuple(data.keys())).replace("'",'') + str('{}').format(tuple(data.values()))

        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return int(self.cursor.lastrowid)
        except Exception as e:
            self.conn.rollback()
            print(e)
            return False

    # 删除记录
    def delete(self,tableName,restrication_str):
        sql = 'DELETE FROM {} WHERE {}'.format(tableName,restrication_str)
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return int(self.cursor.lastrowid)
        except Exception as e:
            self.conn.rollback()
            print(e)
            return False


    # 删除表
    def delete_table(self,tablename):
        sql = 'DROP TABLE {} ;'.format(tablename)
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return int(self.cursor.lastrowid)
        except Exception as e:
            self.conn.rollback()
            print(e)
            return False

    # 格式化表
    def foramt_tab(self,tablename):
        sql = 'trncate table {}'.format(tablename)
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return int(self.cursor.lastrowid)
        except Exception as e:
            self.conn.rollback()
            print(e)
            return False


    # 执行sql语句
    def query(self,sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return int(self.cursor.lastrowid)
        except Exception as e:
            print(e)
            self.conn.rollback()
            return False

# 测试
from mysqldemo.MySqlAPI_demo import MysqlDemo
mysql = MysqlDemo('host','username','passwd','dbname')
# print(mysql)
# 插入
# for i in range(10):
#     data = {
#         'FIRST_NAME':'{}'.format(i),
#         'LAST_NAME':'XIAOLIU',
#         'AGE':18,
#         'SEX':'W',
#     }
#     mysql.insert('ZGDL',data)

# 读取
# sql = 'select * from ZGDL'
# mysql.get_one(sql)
# mysql.get_all(sql)

# 更新
# data = {
#     'FIRST_NAME':"'12138'",
#     'LAST_NAME':"'xxl'",
#     'AGE':20,
# }
# mysql.update('ZGDL',data,'FIRST_NAME = 12138')

# 删除数据
# mysql.delete('ZGDL','FIRST_NAME=12138')
发布了22 篇原创文章 · 获赞 0 · 访问量 451

猜你喜欢

转载自blog.csdn.net/qq_43227756/article/details/104515311