Python3使用PyMySQL连接数据库

Python3使用PyMySQL连接数据库

首先下载 PyMySQL。
PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL


PyMySQL安装

在终端输入 cd#将pymysql文件夹直接拖入终端(获得文件夹路径)#回车
输入 python3 setup.py install

WuyuedeMacBook-Pro:PyMySQL-master wuyue$ cd /Users/wuyue/Downloads/PyMySQL-master
WuyuedeMacBook-Pro:PyMySQL-master wuyue$ python3 setup.py install

开始跑了,出现

Finished processing dependencies for PyMySQL==0.9.2

安装成功


进入python shell输入import pymysql

WuyuedeMacBook-Pro:PyMySQL-master wuyue$ python3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymysql
>>> 

查询数据库VERSION


>>> import pymysql as p
>>> conn = p.connect ("127.0.0.1","root","may714282960921","KATNISS")
>>> cursor = conn.cursor()
>>> cursor.execute ("SELECT VERSION()")
1
>>> print ("database version : %s" % cursor.fetchone())
database version : 8.0.11

补充:python之cursor() — 数据库连接操作
1、建立数据库连接
import MySQLdb
conn=MySQLdb.connect(host=”localhost”,user=”root”,passwd=”sa”,db=”mytable”)
cursor=conn.cursor()
2、执行数据库操作
n=cursor.execute(sql,param)
我们要使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.
包括两大类:1)执行命令;2)接受返回值;

3、cursor用来执行命令的方法:
callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
  execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
  executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
  nextset(self):移动到下一个结果集
4、cursor用来接收返回值的方法:
fetchall(self):接收全部的返回结果行.
  fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
  fetchone(self):返回一条结果行.
  scroll(self, value, mode=’relative’):移动指针到某一行.如果mode=’relative’,则表示从当前所在行移动value条,如果mode=’absolute’,则表示从结果集的第一 行移动value条.
5、关闭数据库连接
需要分别的关闭指针对象和连接对象.他们有名字相同的方法
cursor.close()
conn.close()


从表EMPLOYEE中选取所有的列

这个是MAC MySQL的可视化工具Workbench的界面,下一篇写Workbench的安装和使用好了:)

>>> cursor.execute("SELECT * FROM EMPLOYEE")
1
>>> print(fetchall())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fetchall' is not defined
>>> print(cursor.fetchall())
(('Mac', 'Mohan', 20, 'M', 2000.0),)

创建数据库new_database、数据表new_table、设置字段类型

>>> cursor.execute("drop database if exists new_database")
1
>>> cursor.execute("create database new_database")
1
>>> cursor.execute("use new_database")
0
>>> sql = """create table new_table (
... FIRST_NAME CHAR(20) NOT NULL,
... LAST_NAME CHAR(20) NOT NULL,
... AGE INT,
... SEX CHAR(1),
... INCOME FLOAT )"""
>>> cursor.execute(sql)
0

好了,可以慢慢玩了~
这一篇是和同学一起自学写出来的,如有错误,还请各位大佬指正!

附上链接-python之cursor() — 数据库连接操作
https://blog.csdn.net/djy37010/article/details/70161218?locationNum=6&fps=1

猜你喜欢

转载自blog.csdn.net/katniss_wuyuechen/article/details/81286347