python3 连接MySQL数据库

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq262593421/article/details/102691270

一,代码

#-*- encoding: utf-8 -*-
'''
DBUtil.py
Created on 2019/10/22 14:27
Copyright (c) 2019/10/22, Google Copy right
@author: com
'''

# import MySQLdb

import pymysql

# 打开数据库连接
conn = pymysql.connect(host="localhost",user="root",passwd="123456",db="test",charset="utf8")
# conn = pymysql.connect("localhost", "root", "123456", "test")

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()

# 使用 execute()  方法执行 SQL 查询
cursor.execute("select version()")

# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()

# 输出MySQL版本号
print("MySQL version : %s " % data)

# 查询语句
sql = "select * from User"

# 执行sql语句
cursor.execute(sql)

# 查询多条数据,返回结果
result = cursor.fetchall()

# 循环遍历结果集
for row in result:
    print("%d \t %s \t  %d" % row)

# 关闭数据库连接
conn.close()

2、执行结果

猜你喜欢

转载自blog.csdn.net/qq262593421/article/details/102691270
今日推荐