zoukankan      html  css  js  c++  java
  • day25-20180529笔记

    笔记:复习Python3操作Mysql新建表、插入数据、查询数据

    一、复习Python3操作Mysql新建表、插入数据、查询数据

    什么是 PyMySQL?

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

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

    PyMySQL 安装

    在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。

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

    如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL:

    $ pip install PyMySQL

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

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

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

    注意:请确保您有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

    数据库连接

    连接数据库前,请先确认以下事项:

    • 创建数据库 sqlalchemy
    • 在sqlalchemy数据库中创建了表 dictionary
    • dictionary表字段为 id(主键), key和 value。
    • 连接数据库sqlalchemy使用的用户名为 "user1" ,密码为 "123456",你可以可以自己设定或者直接使用root用户名及其密码,Mysql数据库用户授权请使用Grant命令。
    • 在你的机子上已经安装了 Python MySQLdb 模块。
     练习:读取 dictionary.txt 文件,一行一行的插入到sqlalchemy库的dictionary表下。
    登录到数据库,创建数据库 sqlalchemy
    mysql> CREATE DATABASE IF NOT EXISTS sqlalchemy DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

     mysql> flush privileges;

      mysql> grant all on *.* to user1 identified by '123456';

    创建表 

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Time    : 2018/5/30 22:11
    # @Author  : yangyuanqiang
    # @File    : createtable.py
    
    # 创建表
    
    import codecs
    
    from sqlalchemy import Column, MetaData, Table
    from sqlalchemy import Integer
    from sqlalchemy import String
    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    
    engine = create_engine('mysql+pymysql://user1:123456@192.168.3.11/sqlalchemy?charset=utf8')
    
    metadata = MetaData(engine)
    
    dictionary = Table('dictionary', metadata,
                 Column('id', Integer, primary_key=True),
                 Column('key', String(50)),
                 Column('value', String(50))
                 )
    metadata.create_all(engine)
    
    print(Table)

    以上实例输出的结果

    <class 'sqlalchemy.sql.schema.Table'>

    查看数据库

    mysql> show tables;
    +----------------------+
    | Tables_in_sqlalchemy |
    +----------------------+
    | dictionary           |
    +----------------------+
    1 row in set (0.00 sec)
    
    mysql> 

    插入数据

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Time    : 2018/5/30 22:11
    # @Author  : yangyuanqiang
    # @File    : insertdata.py
    
    
    # 插入数据
    
    import codecs
    
    from sqlalchemy import Integer, Column, String, create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    
    
    engine = create_engine('mysql+pymysql://user1:123456@192.168.3.11/sqlalchemy?charset=utf8')
    
    Base = declarative_base()
    class Dictionary(Base):
        __tablename__ = 'dictionary'
        id = Column(Integer, primary_key=True)
        key = Column(String(50))
        value = Column(String(50))
    
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    
    
    
    
    
    
    class HandleData(object):
        def __init__(self, dataFile):
            self.dataFile = dataFile
        def make_data_to_str(self):
            with codecs.open(self.dataFile, encoding='utf-8') as file:
                for (num, value) in enumerate(file):
                    line = value.strip().split()
                    diction =Dictionary(id=num+1, key=line[0], value=line[1])
                    session.add(diction)
            session.commit()
    
    
    handleData = HandleData('dictionary.txt')   #数据
    handleData.make_data_to_str()
    session.close()

    统计插入的数据总数

    mysql> select count(*) from dictionary;
    +----------+
    | count(*) |
    +----------+
    |     7988 |
    +----------+
    1 row in set (0.00 sec)
    
    mysql> 

    查询数据,模糊匹配查询

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Time    : 2018/5/30 22:12
    # @Author  : yangyuanqiang
    # @File    : selectdata.py
    
    
    # 查询数据
    
    from sqlalchemy import create_engine, Integer, Column, String
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    engine = create_engine('mysql+pymysql://user1:123456@192.168.3.11/sqlalchemy?charset=utf8')
    
    Base = declarative_base()
    class Dictionary(Base):
        __tablename__ = 'dictionary'
        id = Column(Integer, primary_key=True)
        key = Column(String(50))
        value = Column(String(50))
    
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    
    word = input("please input your a word:")
    result =session.query(Dictionary).filter(Dictionary.key.like("%{0}%".format(word))).all()
    for each in result:
        print(each.id, each.key, each.value)

    以上实例输出的结果,模糊匹配,只要匹配“where”的都会输出来

    please input your a word:where
    345 anywhere adv.无论何地
    2354 elsewhere adv.在别处
    2533 everywhere adv.处处,到处
    4808 nowhere adv.哪儿也不
    6634 somewhere adv.某地,到某处
    7826 where adv.哪里
    7827 whereabouts n.下落
    7828 whereas conj.而,却
    7829 whereby adv.借此
    7830 wherein adv.在何处
    7831 wherever adv.无论哪里

    总结:

    1、熟悉SQL语法增、删、改、查;

    2、了解数据库表结构;

    3、写代码先从简单的开始写,测试,最后再优化代码。




  • 相关阅读:
    哦!Python爬虫的这4种方法优缺点你知道吗?
    当你认为Python程序慢时!几个方法你使用了吗!
    Python数据可视化你了解多少!看一下这些是你了解的吗 ?
    王者英雄你喜欢那个!利用Python网络爬虫教你抓取喜欢的英雄图片!
    使用Python时多少有人走过的坑!你是否也遇到过呢!
    Python的68个内置函数你真正的了解多少!建议合理的运用起来!
    使用Python 进行字串格式化的几种方式!你平时是否使用过呢!
    在找工作吗?今天教你使用Python网络爬虫获取招聘信息!来体验一下
    Azure上A/D系列虚拟机到DS系列迁移(1)
    超大文件上传到Azure Linux虚拟机最佳实践
  • 原文地址:https://www.cnblogs.com/ivan-yang/p/9113842.html
Copyright © 2011-2022 走看看