Python3连接MySQL数据库及基本操作

一、起因
做接口测试,需要提前在数据库插入预先准备好的测试数据,故,笔者做整理出用Python3连接MySQL数据库及其基本的操作法方法

二、说 明
Python3连接MySQL数据库使用到的第三方库为:PyMySQL,当然,安装也很简单

# 直接pip安装即可
pip install PyMySQL

三、使 用
1.Python3连接连接数据库


```python
#!/usr/bin/python
# coding=utf-8
# 导入pymysql库
from pymysql import connect

try:
    conn = connect(
        host='10.*.*.***',
        port=3306,
        user='user name',
        password='user passwd',
        db='database',
        charset='utf8')
    cursor = conn.cursor()
except Exception as e:
    print(e)
else:
    print('Connect Success:%s' % cursor)

# result
>> Connect Success:<pymysql.cursors.Cursor object at 0x000002BB65E0D828>

``
2.数据库基本操作:增、删、改、查
实际上只需要定义一个执行SQL的方法,具体运行对应的增删改查SQL语句即可

#!/usr/bin/python
# coding=utf-8
# 导入pymysql库
from pymysql import connect

......
# 连接数据库
try:
    conn = connect()
......

def execute_sql(command, sql):
    """
    查询数据库数据
    :param command:
    :param sql:
    :return:
    """
    if command in ('SELECT', 'select'):
        # 如果为查询指令
        sql = sql.encode('utf-8')
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
            return result
        except Exception as e:
            print(e)
        finally:
            conn.close()
    elif command in ('delete', 'DELETE', 'update', 'UPDATE', 'insert', 'INSERT'):
        # 如果为增删改
        sql = sql.encode('utf-8')
        try:
            cursor.execute(sql)
            conn.commit()
        except Exception as e:
           # 如果失败则回滚
            conn.rollback()
            print(e)
        finally:
            conn.close()
    else:
        print('Command Error!')

if __name__ == '__main__':

    sel_sql = 'SELECT * FROM tb_user WHERE phone = "182********";'
    print(execute_sql('select', sel_sql))

四、最 后
撒花~~~~结束~

你可能感兴趣的:(Python3连接MySQL数据库及基本操作)