zoukankan      html  css  js  c++  java
  • 使用Connector 或者Python连接MySQL以及查询数据

    mysql-connector是一个Python模块,它在Python中重新实现MySQL协议,它比较慢,但不需要C库,因此更便携.
    mysql-connector 是 MySQL 官方提供的驱动器。
    1、.安装
    python -m pip install mysql-connector

    2、使用

    数据库连接

    需要导入驱动模块,mysql.connector,并使用connector模块中的connect方法连接数据库,

    查看源码 def connect(*args, **kwargs),该方法中允许传入元祖模式参数,和字典类型参数,

    即就是:

    #字典
    localdb=mysql.connector.connect(    
        host='127.0.0.1',
        user='root11',
        passwd='root22')
     # 元祖
    localdb=mysql.connector.connect('127.0.0.1','root11','root22)

    例一

    import mysql.connector 
    localdb=mysql.connector.connect(
        host='127.0.0.1',
        user='root11',
        passwd='root22')
    print(localdb)
    mycursor=localdb.cursor()
    mycursor.execute("CREATE DATABASE python3sql")
    mycursor.execute("show databases")
    for x in mycursor:
        print(x)

    数据库操作

    正如例一,创建一个cursor实例来执行数据库操作。

    插入:在执行插入语句时候,数据库表有更新,需要像数据库提交事务,

    mydb.commit()    # 数据表内容有更新,必须使用到该语句

    此处插入可以进行多数据插入,使用 mycursor.executemany(sql,val2) 方法。
    删除:同插入
    更新:同插入
    查询:在执行查询语句时候,需要返回查询结果,
    全部返回  fetchall(self),
    部分返回  fetchmany(self,size=1),
    单数据返回  fetchone(self)
    ---------------------
    作者:IT_xiaocai27
    来源:CSDN
    原文:https://blog.csdn.net/weixin_38328865/article/details/84983282
    版权声明:本文为博主原创文章,转载请附上博文链接!
    以上是我看到一个博主写的 我觉得易懂
    • 1.使用connect()构造函数
    import mysql.connector
    
    cnx = mysql.connector.connect(user='scott', password='password',
                                  host='127.0.0.1',
                                  database='employees')
    cnx.close()
    • 使用connection.MySQLConnection() 类创建连接对象
    from mysql.connector import (connection)
    
    cnx = connection.MySQLConnection(user='scott', password='password',
                                     host='127.0.0.1',
                                     database='employees')
    cnx.close()
    • 在字典中定义连接参数并使用 **运算符
    import mysql.connector
    
    config = {
      'user': 'scott',
      'password': 'password',
      'host': '127.0.0.1',
      'database': 'employees',
      'raise_on_warnings': True
    }
    
    cnx = mysql.connector.connect(**config)
    
    cnx.close()

    处理链接错误使用try语句并使用error.Error异常捕获所有错误

    import mysql.connector
    from mysql.connector import errorcode
    
    try:
      cnx = mysql.connector.connect(user='scott',
                                    database='employ')
    except mysql.connector.Error as err:
      if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
      elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
      else:
        print(err)
    else:
      cnx.close()


    2.使用Connector / Python查询数据
    import datetime
    import mysql.connector
    
    cnx = mysql.connector.connect(user='scott', database='employees')
    cursor = cnx.cursor()
    
    query = ("SELECT first_name, last_name, hire_date FROM employees "
             "WHERE hire_date BETWEEN %s AND %s")
    
    hire_start = datetime.date(1999, 1, 1)
    hire_end = datetime.date(1999, 12, 31)
    
    cursor.execute(query, (hire_start, hire_end))
    
    for (first_name, last_name, hire_date) in cursor:
      print("{}, {} was hired on {:%d %b %Y}".format(
        last_name, first_name, hire_date))
    
    cursor.close()
    cnx.close()
    
    
    
    
    
  • 相关阅读:
    harbor私有仓库搭建
    为普通用户添加sudo权限
    进程节点占用磁盘空间
    influxdb做prometheus永久存储
    prometheus监控linux进程
    Redis一主两从搭建
    ELK搭建
    redis geo操作
    k8s 1.16.3 yaml声明变化
    k8s启动Pod遇到CrashLoopBackOff的解决方法
  • 原文地址:https://www.cnblogs.com/EST-woah/p/10666608.html
Copyright © 2011-2022 走看看