首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python访问数据库Mysql

Python访问数据库Mysql

作者头像
老七Linux
发布2018-05-09 17:17:35
5.8K0
发布2018-05-09 17:17:35
举报

安装MySQL驱动

由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。

Python3以后好像是不支持MySQLdb了,可以是用pymysql包,可以直接通过pymysql进行使用。

pip install pymysql

MySQLdb 只适用于python2.x,发现pip装不上。它在py3的替代品是:

import pymysql

Mysql的事物

在 MySQL 命令行的默认设置下,事务都是自动提交的,即执行 SQL 语句后就会马上执行 COMMIT 操作。因此要显式地开启一个事务务须使用命令 BEGIN 或 START TRANSACTION,或者执行命令 SET AUTOCOMMIT=0,用来禁止使用当前会话的自动提交。

MYSQL 事务处理主要有两种方法:

1、用 BEGIN, ROLLBACK, COMMIT来实现

BEGIN 开始一个事务
ROLLBACK 事务回滚
COMMIT 事务确认

2、直接用 SET 来改变 MySQL 的自动提交模式:

SET AUTOCOMMIT=0 禁止自动提交
SET AUTOCOMMIT=1 开启自动提交
查看Mysql 是否开启了事务(默认自动开启的)
mysql> show variables like 'auto%';
Mysql的常用操作
授权超级用户:
grant all privileges on *.* to 'tangnanbing'@'%' identified by '[email protected]' with grant option;
查看库:
show databases;
查看都有哪些库  show databases;
查看某个库的表 use db; show tables \G; 
查看表的字段,或者表的结构 desc tb;
查看建表语句 show create table tb;
当前是哪个用户  select user();
当前库 select database();
创建库 create database db1; 
创建表 create table t1 (id int, name char(40) adress varchar(30));  
char(10)              'aaa       '
varchar(10)          'aaa'
查看数据库版本 select version(); 
查看mysql状态 show status;
修改mysql参数 show variables like 'max_connect%'; set global max_connect_errors = 1000; 
查看mysql队列 show processlist; 
select * from information_schema.processlist where info is not null;
sleep的可以忽略,qurey查询的才有

创建普通用户并授权 grant all on *.* to databases1.user1 identified by '123456'; 
grant all on db1.* to 'user2'@'10.0.2.100' identified by '111222';

grant all on db1.* to 'user3'@'%' identified by '231222';


更改密码 UPDATE mysql.user SET password=PASSWORD("newpwd") WHERE user='username' ;   

查询 select count(*) from mysql.user; select * from mysql.db; select * from mysql.db where host like '10.0.%'; 

插入 update db1.t1 set name='aaa' where id=1;  

清空表 truncate table db1.t1; 

删除表 drop table db1.t1; 

删除数据库 drop database db1; 

修复表 repair table tb1 [use frm];

查看权限show grants for [email protected]'localhost';

mysql -uroot -p1234556 -e "select user,host,password into outfile '/home/mysql/1.txt' from mysql.user;";
使用python 连接并操作数据库:

连接数据库前,请先确认使用如下账号是否可以正常连接。

import pymysql

conn = pymysql.connect(host = "192.168.161.128", port = 3306, user = "root", passwd = "asd9577", db = "jumpserver")

cus = conn.cursor()

sql = "select * from settings;"

cus.execute(sql)
result = cus.fetchall()
print(result)

cus.close()
conn.close()

输出:
((1, 'TERMINAL_ASSET_LIST_SORT_BY', '"hostname"', 'default', 1, ''), (2, 'TERMINAL_HEARTBEAT_INTERVAL', '5', 'default', 1, ''), (3, 'TERMINAL_PASSWORD_AUTH', 'true', 'default', 1, ''), (4, 'TERMINAL_PUBLIC_KEY_AUTH', 'true', 'default', 1, ''), (5, 'TERMINAL_COMMAND_STORAGE', '{"default": {"TYPE": "server"}}', 'default', 1, ''), (6, 'TERMINAL_REPLAY_STORAGE', '{"default": {"TYPE": "server"}}', 'default', 1, ''))

详细分析:

什么是游标?

游标(cursor)是系统为用户开设的一个数据缓冲区,存放SQL语句的执行结果。

import pymysql

# 打开数据库连接
conn = pymysql.connect(host = "192.168.161.128", port = 3306, user = "root", passwd = "asd9577", db = "jumpserver")

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

# 需要执行的sql命令
sql = "select * from settings;"

# 使用 execute() 方法执行 SQL 查询 
cus.execute(sql)

# 使用 fetchone() 方法获取单条数据
result = cus.fetchall()

# 输出结果
print(result)

# 关闭游标连接
cus.close()

# 关闭数据库连接
conn.close()

但是虽然如上方法能满足咱们的日常简单需求,如果需要对数据库进行批量处理,我们就需要写多次 数据库连接,效率很低,所以我们一般都是这样写:

import pymysql

class IfConnect(object):
    def __init__(self):
        self.dbConfigure = {
            "host": "192.168.161.128",
            "port": "3306",
            "user": "root",
            "passwd": "asd9577",
            "db": "jumpserver"
        }
        self.conn = pymysql.connect(**self.dbConfigure)

    def select(self):
        # conn = pymysql.connect(**self.dbConfigure)
        cur = self.conn.cursor()
        sql = "select version();"
        cur.execute(sql)
        result = cur.fetchall()
        print(result)

if __name__ == '__main__':
    eee = IfConnect()
    eee.select()

这样就可以随意的去定义多个 select 或者 update 或者 insert!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017/05/06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装MySQL驱动
  • Mysql的事物
    • MYSQL 事务处理主要有两种方法:
      • 查看Mysql 是否开启了事务(默认自动开启的)
    • Mysql的常用操作
      • 使用python 连接并操作数据库:
      相关产品与服务
      云数据库 SQL Server
      腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档