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;
""")

运行结果:

相关推荐
Warson_L16 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅16 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅16 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L17 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅17 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L18 小时前
python的类&继承
python
Warson_L18 小时前
类型标注/type annotation
python
ThreeS20 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵21 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏