赞
踩
pip install mysql-connector-python
pip install pymysql
create database sqltest;
use sqltest;
- CREATE TABLE articles (
- -> id INT,
- -> projectid INT,
- -> authorlastname VARCHAR(50),
- -> pub_year YEAR,
- -> title VARCHAR(200),
- -> abstract TEXT,
- -> journal VARCHAR(100),
- -> impact FLOAT,
- -> includecriteria VARCHAR(100)
- -> );
建立好后查看表:
desc articles;
创建表成功
打开vscode进行python连接mysql数据库时出现报错,根据[1]可知是因为自己配置过的虚拟环境基本上都使用的python3.9至于当前vscode运行并没有在安装了pymsql的环境内。
如下图所示,安装的pymysql不在vscode运行的环境,在另一个地方
所以现在打算按照[2]的教程进行尝试。
在扩展下载安装相关服务
安装好后会发现有mysql一栏
点“+”号按照提示依次输入
localhost
root
密码
3306
无(没有特别说明,按enter即可)
成功,能看到之前自己建立的sqltest数据库
在vscode的terminal中输入mysql的安装包下载
python -m pip install mysql-connector
发现还是不行
直到[3]确定了的确是解释器的问题,因为[1]说得有点突兀,没理解到意思。一切关键在运行的环境里
需要打开解释器,打开comand panel
Ctrl+shift+p
选择所示对应的环境
成功解除报错
运行一组代码将进行测试,顺利连接
- #! /usr/bin/python
- # -*- coding: UTF-8 -*-
-
- """
- 测试
- pymysql 的代码还是很简单的,
- 以下代码分别为连接mysql 获得connection, 从connection 获得cursor 进行操作,
- 都是固定套路:
- """
-
- import mysql.connector
- import pymysql
-
-
- host = 'localhost'
- port = 3306
- db = 'sqltest'
- user = 'root'
- password = 'muren123'
-
-
- # ---- 用pymysql 操作数据库
- def get_connection():
- conn = pymysql.connect(host=host, port=port, db=db, user=user, password=password)
- return conn
-
-
- def check_it():
-
- conn = get_connection()
-
- # 使用 cursor() 方法创建一个 dict 格式的游标对象 cursor
- cursor = conn.cursor(pymysql.cursors.DictCursor)
-
- # 使用 execute() 方法执行 SQL 查询
- cursor.execute("select count(id) as total from articles")
-
- # 使用 fetchone() 方法获取单条数据.
- data = cursor.fetchone()
-
- print("-- 当前数量: %d " % data['total'])
-
- # 关闭数据库连接
- cursor.close()
- conn.close()
-
-
- if __name__ == '__main__':
- check_it()

因为建的是空白表,的确是0
测试结束。顺利连接mysql表
[1] 关于安装好pymysql但import时显示No module named ‘pymysql‘问题:https://blog.csdn.net/weixin_45818508/article/details/108091651
[2] mysql下载->vscode配置->环境变量设置:https://blog.csdn.net/Ashiu/article/details/124221842
[3] Vscode设置python解释器:https://blog.csdn.net/weixin_43301333/article/details/120691962
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。