python连接数据库

python连接mysqql的流程
1、创建数据连接对象
2、获取数据库操作对象
3、写sql语句
4、解析插叙结果
5、关闭数据库连接对象
#安装连接mysql的依赖
pip install pymysql

#导入mysql的依赖
import pymysql

#1.创建数据库的连接对象
connect = pymysql.connect(
    	user='root',
        password='123456',
        host='master',
        port=3306,
        database='数据库名',
        charset='utf8'
   
)
# 本地要配置hosts映射 C:\Windows\System32\drivers\etc\hosts  	# 用VSCode打开修改
  # 192.168.17.100 master
  # 192.168.17.110 node1
  # 192.168.17.120 node2
#2.获取数据操作对象
cursor = connect.cursor()

#sql语句的书写
cursor.execute('sql')

#增删改语句需进行提交
connect.commit()

#获取查询结果
cursor.fetchone()
cursor.fetchmany()
cursor.fetchall()

#关闭连接释放资源
cursor.close()
conenct.close()
posted @ 2024-01-31 19:58  low-reed  阅读(7)  评论(0)    收藏  举报