Python与数据库Mysql连接及操作方法

Python与数据库Mysql连接及操作方法


目录

配置pip

连接需要第三方库---pymysql

python 复制代码
pip install mysql

连接

使用IP地址连接

格式:
pymysql.connect(
user = ' 用户名root'
password = '密码123456'
host = 'xxx.xxx.xxx.xx Ip地址'
batabase = '已创建好的数据库'
port = '端口'
charset = '编码utf8'
)

代码展示:

python 复制代码
conn = pymysql.connect(
    user='root',
    password='123456',
    host='192.123.123.123',
    database='car_infor',
    port=3306,
    charset='utf8'
)

其中database=' '的内容,必须是已经创建完成、存在的数据库。

运行结果:

配置后使用机名连接

hosts映射

在C盘中Windows下system32下drivers下etc下的hosts文件添加IP地址和命名

C:\Windows\System32\drivers\etc hosts文件

使用visualstudio code编辑,添加代码
IP地址 命名

如:192.123.123.123 master

代码展示:

python 复制代码
import pymysql
#建立联系
conn = pymysql.connect(
    user='root',
    password='123456',
    # 为了让window认识master主机,我们需要配置hosts映射
    # C:\Windows\System32\drivers\etc\hosts
    host='master',
    database='car_infor',
    port=3306,
    charset='utf8'
)

运行结果:

执行操作

  • 创建数据库操作对象
    cur = conn.cursor()
  • 编写sql语句
    cur.execute( " sql语句 ")
  • 提交事务,如果有增删改需求,要提交
    conn.commit()

代码展示:

python 复制代码
import pymysql
#建立联系
conn = pymysql.connect(
    user='root',
    password='123456',
    # 为了让window认识master主机,我们需要配置hosts映射
    # C:\Windows\System32\drivers\etc\hosts
    host='master',
    database='car_infor',
    port=3306,
    charset='utf8'
)
#创建数据库操作对象
cur = conn.cursor()
#编写是sql语句,至少双引号,或三双、三单
#创建一个表
cur.execute( """
create table a1(
num1 int,
num2 int
)default charset=utf8;
""")

运行结果:

相关推荐
vivo互联网技术2 小时前
从 10 分钟到 1 秒:ES 深度分页任意跳页的三轮优化实战
服务器·数据库·redis·elasticsearch·深度分页
咕白m6252 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
数据技术说2 小时前
MySQL 迁移实战——如何实现真正的"零改造"平滑切换
mysql
倔强的石头_17 小时前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
SelectDB19 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵2 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li2 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员