查询数据库,首先需要与数据库的连接

import 模块MySQLdb

#mysqldb
import MySQLdb

连接数据库,看看连接本地数据库

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

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

# 使用execute方法执行SQL语句
cursor.execute("SELECT * FROM sr_area")

可正常连接到本地数据库

现在连接其他数据库

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

这里写图片描述

该数据库的端口不是默认的3306,而是3307,查看源码定义端口的参数

这里写图片描述

故增加port参数

#打开数据库连接
conn = MySQLdb.connect(host="xxx.xxx.xxx.xxx",port="3307",user="root",passwd="pwd",db="sr",charset="utf8")

修改后重新执行,仍然报错

这里写图片描述

参数类型不匹配,port为integer,刚刚传的参数为port="3307" ,字符串类型

#打开数据库连接
conn = MySQLdb.connect(host="xxx.xxx.xxx.xxx",port=3307,user="root",passwd="pwd",db="sr",charset="utf8")

修改后,可正常连接数据库

Logo

更多推荐