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

运行结果:

相关推荐
曲幽3 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
xieliyu.3 小时前
Java算法精讲:双指针(二)
java·开发语言·算法
素材积累3 小时前
博士后出站来深可申请的项目补贴等
数据库
装不满的克莱因瓶4 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..4 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
雪的季节4 小时前
RabbitMQ详解
开发语言
金銀銅鐵4 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf4 小时前
Python 模块与包的导入导出
前端·后端·python
_1_75 小时前
SQL Server 磁盘满了 收缩日志
数据库·sqlserver
ice8130331815 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib