pyMySQL安装(python连接mysql)

什么是 PyMySQL?

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。



几种安装方式:

1、使用开发工具直接导包,我的ide是PyCharm, File--->project Interpreter,

操作如图:


安装成功即可,然后在页面引入包就可以使用了,引用:

import pymysql

2、使用命令pip命令安装:

扫描二维码关注公众号,回复: 299488 查看本文章
pip install PyMySQL
查看是否安装成功:
pip show PyMySQL

3、如果你的系统不支持 pip 命令,可以使用以下方式安装:

1)、使用 git 命令下载安装包安装(你也可以手动下载):

$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL/
$ python3 setup.py install

2)、如果需要制定版本号,可以使用 curl 命令来安装:

$ # X.X 为 PyMySQL 的版本号
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz
$ cd PyMySQL*
$ python3 setup.py install
$ # 现在你可以删除 PyMySQL* 目录


注意:请确保您有root权限来安装上述模块。

安装的过程中可能会出现"ImportError: No module named setuptools"的错误提示,意思是你没有安装setuptools,你可以访问https://pypi.python.org/pypi/setuptools 找到各个系统的安装方法。

Linux 系统安装实例:

$ wget https://bootstrap.pypa.io/ez_setup.py
$ python3 ez_setup.py


连接例子:

#coding : utf-8

import pymysql
'''
import pymysql
pymysql:pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本
'''
#打开数据库连接
conn= pymysql.connect(
        host='localhost',
        port = 9521,
        user='root',
        passwd='111111',
        db ='test',
        charset = 'utf-8'
        )
cur = conn.cursor()

#创建数据表
cur.execute("create table a_student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一条数据
cur.execute("insert into a_student values('2','Tom','3 year 2 class','9')")
#修改查询条件的数据
cur.execute("update a_student set class='3 year 1 class' where name = 'Tom'")
#删除查询条件的数据
#cur.execute("delete from a_student where age='9'")

cur.close()
conn.commit()
conn.close()
 
 





猜你喜欢

转载自blog.csdn.net/register_2/article/details/79986624