西琳的博客
发布文章
关于西琳
试验场
Edit "pymysql"
标题
内容
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2 中则使用 mysqldb。PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。 #### 连接数据库 ``` import pymysql conn = pymysql.connect( host='localhost', port=3306, user='root', password='password', charset='utf8mb4' ) print(conn.get_server_info()) cursor = conn.cursor() conn.select_db("mytable") cursor.execute('SELECT * FROM mytable') result : tuple = cursor.fetchall() cursor.close() conn.close() ``` ### 执行SQL语句 一旦建立了与数据库的连接,我们就可以执行各种SQL操作,例如插入、更新、删除和查询等。以下是一些常见的SQL操作示例: 插入数据 ``` sql = "INSERT INTO mytable (name, age) VALUES ('John', 25)" cursor.execute(sql) conn.commit() ``` 更新数据 ``` sql = "UPDATE mytable SET age = 26 WHERE name = 'John'" cursor.execute(sql) conn.commit() ``` 删除数据 ``` sql = "DELETE FROM mytable WHERE name = 'John'" cursor.execute(sql) conn.commit() ``` 查询数据 ``` sql = "SELECT * FROM mytable" cursor.execute(sql) result = cursor.fetchall() for row in result: print(row) ```
提交
搜索
首页
发布文章
快捷导航
个人中心