python通过connect对象连接数据库对吗_python连接Mysql数据库

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

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

PyMySQL安装

1. pip安装

$ pip install PyMySQL

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

$ git clone https://github.com/PyMySQL/PyMySQL

$ cd PyMySQL/

$ python3 setup.py install

######

安装的过程中可能会出现"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

Python连接MYSQL

Python操作数据库,基本步骤

1. 导入相应的python模块

2. 使用connect函数连接数据库,返回一个connection对象

3. 通过connection对象的cursor方法,返回一个cursor对象

4. 通过cursor对象的execute方法执行sql语句

5. 如果执行的是查询语句,通过cursor对象的fetchall语句获取返回结果

6. 调用cursor对象的close方法关闭cursor

7. 调用connection对象的close方方法关闭数据库连接

连接mysql数据库

1. 创建测试库

create table employee(

first_name char(10),

last_name char(10),

age int(10),

sex char(10),

income float

);

2. 创建远程连接授权账号

mysql> grant all on *.* to test@'%' identified by 'test123';

Query OK, 0 rows affected (0.14 sec)

mysql> flush privileges;

Query OK, 0 rows affected (0.03 sec)

3. 编写脚本

#!/usr/bin/python3

import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor() # 使用 cursor() 方法创建一个游标对象 cursor

cursor.execute("SELECT VERSION()") #使用 execute() 方法执行 SQL 查询

data = cursor.fetchone() # 使用 fetchone() 方法获取单条数据.

print("Database version :{0}".format(data))

#print("Database version: %s" % data)

db.close()

执行

python3 mysql_con.py

Database version :('5.6.40',)

创建数据库表

import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor()

cursor.execute("DROP TABLE IF EXISTS employee")

sql = """create table employee(

first_name char(10),

last_name char(10),

age int(10),

sex char(10),

income float)"""

cursor.execute(sql)

db.close()

数据库插入操作

import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor()

sql = """insert into employee(first_name,

last_name,age,sex,income)

values('rock','lin',20,'M',2000)"""

try:

cursor.execute(sql)

db.commit() #提交数据库执行

except:

db.rollback() #如果发生错误则回滚

db.close()

数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

fetchone(): 该方法获取下一个查询结果集。结果集是一个对象

fetchall():接收全部的返回结果行.

rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

实例:

import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor()

cursor.execute("select * from employee")

data = cursor.fetchall() #获取SQL语句所有记录

for user in data: #对返回的记录进行遍历

print(user)

db.close()

执行

[root@vm80 db]# python3 mysql_con.py

('rock', 'lin', 20, 'M', 2000.0)

('su', 'tian', 18, 'F', 1000.0)

数据库更新操作

import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor()

sql = "UPDATE employee set age = age + 1 where sex = 'M'" #SQL更新操作

try:

cursor.execute(sql)

db.commit()

except:

db.rollback()

db.close()

验证

mysql> select * from employee;

+------------+-----------+------+------+--------+

| first_name | last_name | age | sex | income |

+------------+-----------+------+------+--------+

| rock | lin | 21 | M | 2000 |

数据库删除操作

import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor()

sql = "delete from employee where age > 20" # SQL 删除语句

try:

cursor.execute(sql)

db.commit()

except:

db.rollback()

db.close()

验证

mysql> select * from employee;

Empty set (0.00 sec)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值