目录 一、最基本的准备 1.1 本地安装Mysql,推荐安装以下其中之一 1.2 安装python软件 二、建立连接 1.1打开PyCharm编程软件 1.2 打开mysql软件,否则连接不上 1.3 在Python环




pip install PyMysql
import pymysql.cursors# 连接数据库connect = pymysql.Connect(    host='127.0.0.1',    port=3306,    user='root',    passwd='123456',    db='test_1',    charset='utf8') 运行上述代码不报错则说明连接成功,若不放心,我们可建表试试,如果在数据库中能够看到所建的表,说明连接成功了。
# 获取游标cursor = connect.cursor()#创建表格sql = "CREATE TABLE test_1(id INTEGER PRIMARY KEY,name TEXT)"try:    cursor.execute(sql)    connect.commit()except:    print("表已存在")print('成功创建表格') 打印结果


如图所示证明,python与mysql连接成功了
# 连接数据库connect = pymysql.Connect(    host='127.0.0.1',    port=3306,    user='root',    passwd='123456',    db='note',    charset='utf8')# 获取游标cursor = connect.cursor()#删除表sql = 'DROP TABLE IF EXISTS student'cursor.execute(sql)connect.commit()print('如果存在表就删除表格')#创建表格sql = "CREATE TABLE student(id INTEGER PRIMARY KEY,name TEXT)"try:    cursor.execute(sql)    connect.commit()except:    print("表已存在")print('成功创建表格')# 插入数据sql = "INSERT INTO student VALUES(%d,'%s')"data = (1, 'student1')cursor.execute(sql % data)connect.commit()print('成功插入', cursor.rowcount, '条数据')# 修改数据sql = "UPDATE student SET name = '%s' WHERE id = %d "data = ('student2', 1)cursor.execute(sql % data)connect.commit()print('成功修改', cursor.rowcount, '条数据')# 查询数据sql = "SELECT * FROM student WHERE id=%d"data = (1,)cursor.execute(sql % data)for row in cursor.fetchall():    print("%s" % str(row))print('共查找出', cursor.rowcount, '条数据')# 删除数据sql = "DELETE FROM student WHERE id = %d LIMIT %d"data = (1, 1)cursor.execute(sql % data)connect.commit()print('成功删除', cursor.rowcount, '条数据')# 事务处理sql_1 = "UPDATE student SET name = name + '1' WHERE id = 1 "try:    cursor.execute(sql_1)except Exception as e:    connect.rollback()  # 事务回滚    print('事务处理失败', e)else:    connect.commit()  # 事务提交    print('事务处理成功', cursor.rowcount)# 关闭连接cursor.close()connect.close() | 参数 | 说明 | 
|---|---|
| host(str) | MySQL服务器地址 | 
| port(int) | MySQL服务器端口号 | 
| user(str) | 用户名 | 
| passwd(str) | 密码 | 
| db(str) | 数据库名称 | 
| charset(str) |   连接编码  | 
| 方法 | 说明 | 
|---|---|
| cursor() | 使用该连接创建并返回游标 | 
| commint() | 提交当前事务 | 
| rollback() | 回滚当前事务 | 
| close() | 关闭连接 | 
| 方法 | 说明 | 
|---|---|
| execute(op) | 执行一个数据库的查询命令 | 
| fetchone() | 取得结果集的下一行 | 
| fetchmany(size) | 获取结果集的下几行 | 
| fetchall() | 获取结果集中的所有行 | 
| rowcount() | 返回数据条数或影响条数 | 
| close() | 关闭游标对象 | 
来源地址:https://blog.csdn.net/qq_58546982/article/details/131019960
--结束END--
本文标题: 如何将python中的数据存储到mysql中
本文链接: https://www.lsjlt.com/news/397785.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0