Python中操作mysql知识(一)

Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口。

Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库:

  • GadFly
  • mSQL
  • MySQL
  • PostgreSQL
  • Microsoft SQL Server 2000
  • Informix
  • Interbase
  • Oracle
  • Sybase

Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同 的方式操作各数据库。

Python DB-API使用流程:

1.    引入API模块。
2.    获取与数据库的连接。
3.    执行SQL语句和存储过程。
4.    关闭数据库连接。
 

什么是MySQLdb?


MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。
如何安装MySQLdb?
为了用DB-API编写MySQL脚本,必须确保已经安装了MySQL。复制以下代码,并执行:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb


如果执行后的输出结果如下所示,意味着你没有安装 MySQLdb 模块:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    import MySQLdb
ImportError: No module named MySQLdb


安装MySQLdb,请访问 http://sourceforge.net/projects/mysql-python ,(Linux平台可以访问:https://pypi.python.org/pypi/MySQL-python)从这里可选择适合您的平台的安装包,分为预编译的二进制文件和源代码安装包。
如果您选择二进制文件发行版本的话,安装过程基本安装提示即可完成。如果从源代码进行安装的话,则需要切换到MySQLdb发行版本的顶级目录,并键入下列命令:

$ gunzip MySQL-python-1.2.2.tar.gz
$ tar -xvf MySQL-python-1.2.2.tar
$ cd MySQL-python-1.2.2
$ python setup.py build
$ python setup.py install

pip好像是不支持安装MySQLdb的,我们可以通过网站下载安装,
下载地址:https://pypi.python.org/pypi/MySQL-python/1.2.5
分别对应有windows和源码安装的方法

安装依赖包:

yum install –y python-devel
yum install –y mysql-devel
yum install –y gcc

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

pip install pymysql

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

Mysql的事务

一般来说,事务是必须满足4个条件(ACID): Atomicity(原子性)、Consistency(稳定性)、Isolation(隔离性)、Durability(可靠性)
1、事务的原子性:一组事务,要么成功;要么撤回。
2、稳定性 : 有非法数据(外键约束之类),事务撤回。
3、隔离性:事务独立运行。一个事务处理后的结果,影响了其他事务,那么其他事务会撤回。事务的100%隔离,需要牺牲速度。
4、可靠性:软、硬件崩溃后,InnoDB数据表驱动会利用日志文件重构修改。可靠性和高速度不可兼得, innodb_flush_log_at_trx_commit选项 决定什么时候吧事务保存到日志里
 

MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> show variables like 'auto%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
| autocommit               | ON    |
| automatic_sp_privileges  | ON    |
+--------------------------+-------+
4 rows in set (0.01 sec)

MariaDB [mysql]> 


安装Mysql

1.上官网,下源码包

2.安装依赖工具:

yum -y install make gcc-c++ cmake bison-devel ncurses-devel libaio libaio-devel perl-Data-Dumper net-tools

3. 解压

rz

cd /usr/local/src

tar xzvf mysql-5.6.32.tar.gz

cd mysql-5.6.32

4.编译:

cmake -DCMAKE_INSTALL_PREFIX=/export/servers/mysql/ -DMYSQL_DATADIR=/export/Data/mysql/data -DSYSCONFDIR=/export/servers/mysql/etc -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_PERFSCHEMA_STORAGE_ENGINE=1 -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DMYSQL_UNIX_ADDR=/export/Data/mysql/tmp/mysql.sock -DENABLED_LOCAL_INFILE=ON -DENABLED_PROFILING=ON -DWITH_DEBUG=0 -DMYSQL_TCP_PORT=3358

DCMAKE_INSTALL_PREFIX

/usr/local/mysql

安装目录

DMYSQL_DATADIR

/usr/local/mysql/data

数据库位置

DSYSCONFDIR

/etc

配置文件位置

DWITH_MYISAM_STORAGE_ENGINE

1

安装myisam存储引擎

DWITH_INNOBASE_STORAGE_ENGINE

1

安装innodb存储引擎

DWITH_MEMORY_STORAGE_ENGINE

1

安装memory存储引擎

DWITH_READLINE

1

快捷键功能

DMYSQL_UNIX_ADDR

/var/lib/mysql/mysql.sock

Unix socket 文件路径

DMYSQL_TCP_PORT

3306

MySQL监听端口

DENABLED_LOCAL_INFILE

1

许从本地导入数据-

DWITH_PARTITION_STORAGE_ENGINE

1

安装数据库分区

DEXTRA_CHARSETS

all

安装所有扩展字符集

DDEFAULT_CHARSET

utf8

使用utf8字符

DDEFAULT_COLLATION

utf8_general_ci

校验字符

如图所示编译成功,每次进行echo $?进行验证

make && make install

5.创建mysql用户=并赋权

useradd mysql -s /sbin/nologin

chown -R mysql:mysql /export/servers/mysql /export/Data/mysql

6.初始化系统表:

cd /export/servers/mysql/scripts

./mysql_install_db --basedir=/export/servers/mysql/ --datadir=/export/Data/mysql/data --user=mysql

mkdir -p /export/servers/mysql/etc

cp /export/servers/mysql/my.cnf

yum remove -y mysql

7.启动mysql

cd /export/servers/mysql

cp support-files/mysql.server /etc/init.d/mysqld

检查配置文件的datadir,basedir等是否正确

service mysqld start

8.检查mysql是否启动成功

ps -ef |grep mysql

netstat -lnp |grep mysql

9.如果启动不了,就在/export/Data/mysql/data找`hostname`.err对应的日志查看

Mysql常用操作

•授权超级用户:

•grant all privileges on *.* to 'fengxiaoqing'@'%' identified by 'admin@123' 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';insert into tb1 (id,name) values(1,'aming');

•更改密码 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 root@'localhost';

•echo "select user,host,password from mysql.user" |mysql -uroot -plingxiangxiang

•mysql -uroot -p1234556 -e "select user,host,password into outfile '/home/mysql/1.txt' from mysql.user;"

Mysql的连接

•1.创建数据库 create database python;

•2. 授权用户

•grant all privileges on *.* to feng@’%’ identified by ‘123456’;

•flush privilege;

•conn=MySQLdb.connect(host="192.168.100.101",user="feng",passwd="123456",db="python",charset="utf8")

比较常用的参数包括:

•host:数据库主机名.默认是用本地主机

•user:数据库登陆名.默认是当前用户

•passwd:数据库登陆的秘密.默认为空

•db:要使用的数据库名.没有默认值

•port:MySQL服务使用的TCP端口.默认是3306,数字类型

•charset:数据库编码

推荐大家使用函数的方式:

def connect_mysql():
    db_config = {
        'host': '192.168.48.128',
        'port': 3306,
        'user': 'xiang',
        'passwd': '123456',
        'db': 'python',
        'charset': 'utf8'
    }
    cnx = MySQLdb.connect(**db_config)
return cnx

游标

游标(Cursor)是处理数据的一种方法,为了查看或者处理结果集中的数据,游标提供了在结果集中一次一行或者多行前进或向后浏览数据的能力。可以把游标当作一个指针,它可以指定结果中的任何位置,然后允许用户对指定位置的数据进行处理

Import…………
if __name__ == '__main__':
    cnx = connect_mysql()
    cus = cnx.cursor()
    sql  = ''' create table test(id int not null);insert into test(id) values (100);'''
    try:
        cus.execute(sql)
        cus.close()
        cnx.commit()
    except Exception as e:
        cnx.rollback()
        print('Error')
        # raise e
    finally:
        cnx.close()

游标常用的方法:
常用方法:
cursor():创建游标对象
Cus = connect_mysql().cursour()
close():关闭此游标对象
excute(sql[, args]):执行一个数据库查询或命令
fetchone():得到结果集的下一行
fetchmany([size = cursor.arraysize]):得到结果集的下几行
fetchall():得到结果集中剩下的所有行
executemany (sql, args):执行多个数据库查询或命令

个人推荐,尽量不使用executemany,通过程序循环不断调用excute函数
 

数据库连接池

import pymysql
from DBUtils.PooledDB import PooledDB

from DBUtils.PooledDB import PooledDB
db_config = {
        "host": "192.168.48.131",
        "port": 3306,
        "user": "xiang",
        "passwd": "xiang",
        "db": "python",
        # "charset": "utf8"
    }

spool = PooledDB(pymysql, 5, **db_config)  # 5为连接池里的最少连接数
# def connect_myssql():
conn = spool.connection()  # 以后每次需要数据库连接就是用connection()函数获取连接
cur = conn.cursor()
SQL = "select * from tmp;"
r = cur.execute(SQL)
r = cur.fetchall()
print(r)
cur.close()
conn.close()

参考文章:http://www.runoob.com/python/python-mysql.html

猜你喜欢

转载自my.oschina.net/u/3804957/blog/1807903