python3连接MySQL数据库简单模板

本篇文python3链接数据库的模板,为急需使用python链接数据库的人准备,复制走改改参数就可以使用,重要代码也做了注释
有关python3连接数据库的详细说明请看这篇python3连接MySQL数据库,并执行数据库的基本增删改查操作

"""首先获取连接对象conn"""

conn = pymysql.connect(
	host="localhost",  # 指示host表明是本地MySQL还是远程
    user="root",  # 用户名
    password="root",  # 密码
    db="db4",  # 要连接的数据库名
    charset="utf8mb4",  # 指定字符集,可以解决中文乱码
    cursorclass=pymysql.cursors.DictCursor
    
"""进行语句的增删改查"""

try:
	with conn.cursor() as cursor:
		sql = "select * from user where id=%s and username=%s"
		result = cursor.execute(sql, ("12", "zhanshen"))  # 在这个括号内传入参数
		# 这里的result只是返回受影响的行数
		res_list = cursor.fetchall()  
		# fetchall可以返回查询的所有结果,结果封装成元祖形式,可以转换成列表形式
		#fetchone()可以只获得结果的第一个结果
	
	with conn.cursor() as cursor:
		sql = "insert into user (username, password) values(%s, %s)"
		result = cursor.execute(sql, ("zhanshen", "123456")) 
		conn.commit()  # 提交事务
finally:
	conn.close()  # 关闭数据库
发布了62 篇原创文章 · 获赞 20 · 访问量 5811

猜你喜欢

转载自blog.csdn.net/weixin_44415928/article/details/104214704
今日推荐