一、起因
做接口测试,需要提前在数据库插入预先准备好的测试数据,故,笔者做整理出用Python3连接MySQL数据库及其基本的操作法方法
二、说 明
Python3连接MySQL数据库使用到的第三方库为:PyMySQL,当然,安装也很简单
复制代码
1
2
3# 直接pip安装即可 pip install PyMySQL
三、使 用
1.Python3连接连接数据库
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22```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语句即可
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45#!/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数据库及基本操作的全部内容,更多相关Python3连接MySQL数据库及基本操作内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复