Python

Python3连接数据库

  1. 如果在外网环境下访问数据库首先要保证数据库允许外伤访问,否则无法连接,设置方法在我的上一面文章中有讲https://shaynerain.com/mysql允许外网访问数据库/
  2. 安装PyMySQL

    管理员下输入pip install PyMySQL

  3. 服务器环境:数据库中新建test数据库,并建立一个user表,填入值


# 打开数据库连接

db = pymysql.connect(“111.111.111.111”,“root”,“password”,“test”)


# 使用cursor()方法获取操作游标

cursor = db.cursor()


# SQL 查询语句

sql = “SELECT * FROM `user`”


try:

cursor.execute(sql)

results = cursor.fetchall()


for row in results:

user = row[0]

password = row[1]


# 打印结果

print (“user=%s, tpassword=%s “ % (user, password))


pass


except:

print (“sql error”)


try:

db.close()


except:

print (“close error”)


pass

闻道有先后 术业有专攻

From: shaynerain.com

By: Shaynerain

3 COMMENTS

LEAVE A RESPONSE

电子邮件地址不会被公开。

Hi, I'm shaynerain, this is my website. www.shaynerain.com