python3-连接mysql

 

 

新建mysql01.ini 

[database1]
host=127.0.0.1
port=3306
user=root
passwd=qwer1234
db=data01
charset=utf8

新建mysql01.py

import pymysql

import configparser
cf =configparser.ConfigParser()
cf.read("/Users/syswin/PycharmProjects/pythons/practicesall/mysql01/mysql01.ini")
# 连接数据库
host = cf.get("database1","host")
port = int(cf.get("database1","port"))
"""port类型为 int"""
user = cf.get("database1","user")
passwd = cf.get("database1","passwd")
db = cf.get("database1","db")
charset = cf.get("database1","charset")
print(host)
print(port)
print(user)
print(passwd)
print(db)
print(charset)


connect = pymysql.Connect(
    host=host,
    port=port,
    user=user,
    passwd=passwd,
    db=db,
    charset=charset
)
# 获取游标
cursor = connect.cursor()

# # 插入数据
# """第一种写法"""
# sql_insert = "insert into table01(id,name) values(4,'name04')"
# cursor.execute(sql_insert)

"""第二种写法"""
sql_insert = "insert into table01(id,name) values(%d,'%s')"
data_insert = (55,'name55')
cursor.execute(sql_insert % data_insert)

connect.commit()
print("成功插入", cursor.rowcount, "条数据")
#

# 删除数据
sql_delete = "delete from table01 where id = 55"
cursor.execute(sql_delete)
connect.commit()

# 查询数据
sql_select = "select * from table01"
cursor.execute(sql_select)

# 获取查询结果
result = cursor.fetchall()
print(result)
print(connect)
print(cursor)
cursor.close()
connect.close()

 

转载于:https://www.cnblogs.com/gaoyuanyuan/p/10161198.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值