1.首先安装第三方插件
pip安装pymysql:
pip install pymysql
pip安装mysql-connector-python:
pip install mysql-connector-python
2.连接数据库
首先要提供数据库信息:地址\端口\用户名\密码
config = {
"host":"xxx.xxx.xxx.xxx", # 地址
"port":3306, # 端口
"user":"test", # 用户名
"password":"123456", # 密码
"database":"database", # 数据库名;如果通过Python操作MySQL,要指定需要操作的数据库
"charset":"utf8"
}
以下用的是pymysql
(1).根据登录的信息,去登录数据库,产生一个数据库连接
conn = pymysql.connect(**config)
(2).产生一个游标,可以获取数据库的操作权限
cursor = conn.cursor()
(3).利用游标进行操作
sql = 'select * from member where id = 123456'
cursor.execute(sql)
(4).获取结果:1.获取单条 ; 2.获取多条; 如果查询需要获取结果
res = cursor.fetchone() # 获取单条
res = cursor.fetchall() # 获取多条
# 以上两种返回的是:单条,一个元组;多条,一个嵌套元组
(5).关掉游标,关掉连接
cursor.close()
conn.close()
3.eg:
import pymysql
from sport_auto_test.common import file_path
from sport_auto_test.common.readConfig import readConfig
class doMysql:
def do_mysql(self,sql):
# 从配置文件里面读取出来--字符串--eval转成字典
config = eval(readConfig().read_config(file_path.db_path,'DB','config'))
# 根据登录的信息,去登录数据库,产生一个数据库连接
conn = pymysql.connect(**config)
# 产生一个游标,可以获取数据库的操作权限
cursor = conn.cursor()
# 利用游标进行操作
cursor.execute(sql)
# 获取结果:1.获取单条 ; 2.获取多条
# res = cursor.fetchone() # 获取单条
res = cursor.fetchall() # 获取多条
# 关掉游标,关掉连接
cursor.close()
conn.close()
return res
if __name__ == '__main__':
sql = 'select * from member where id = 1'
res = doMysql().do_mysql(sql)
print('获取到的数据是:{}'.format(res))
参考:http://www.runoob.com/python3/python-mysql-connector.html
版权声明:本文为qq_38741986原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。