zoukankan      html  css  js  c++  java
  • connector for python

    使用python中的mysql.connector模块操作mysql

    python代码

     
    import mysql.connector                 
    
    # mysql1.py
    config = {
        'host': '127.0.0.1',
        'user': 'root',
        'password': 'root',
        'port': 3306,
        'database': 'test',
        'charset': 'utf8'
    }
    try:
        cnn = mysql.connector.connect(**config)
    except mysql.connector.Error as e:
        print('connect fails!{}'.format(e))
    cursor = cnn.cursor()
    try:
        sql_query = 'select name,age from stu ;'
        cursor.execute(sql_query)
        for name, age in cursor:
            print (name, age)
    except mysql.connector.Error as e:
        print('query error!{}'.format(e))
    finally:
        cursor.close()
        cnn.close()
    复制代码

    操作结果

    (u'xiaoming', 10)
    (u'rose', 18)
    (u'jack', 19)
    (u'fang', 20)
    (u'Liang', 40)
    (u'Age', None)

    更加规范的操作,代码如下

     
    def select2(sql_cmd, param):
        """
        :param sql_cmd sql 命令
        :param param 参数
        """
        try:
            conn = mysql.connector.connect(**config)
        except mysql.connector.Error as e:
            print('connect fails!{}'.format(e))
    
        cursor = conn.cursor()
        try:
            cursor.execute(sql_cmd, param)
        except mysql.connector.Error as e:
            print('connect fails!{}'.format(e))
        finally:
            cursor.close()
            conn.close()
    
    if __name__ ==  '__main__':
        sql_cmd = "insert into stu (name, age, sex) value (%s, %s, %s)"
        param = ('yangguo', 28, 'male')
        select2(sql_cmd=sql_cmd, param=param)    # 将命令和参数分隔开,操作起来更加安全
  • 相关阅读:
    坚持博客
    虚拟机CentOS7.2 1611 Minimal最小化安装后桥接固定ip
    Js 希望某链接只能点击一次
    ThinkPHP3.2 杂记
    Mysql 杂记
    Linux挂载Win共享文件夹 一
    Linux 监测系统资源
    Phpstrom 书签应用
    php默认有最大执行时间
    tp3.2中配置链接多个数据库
  • 原文地址:https://www.cnblogs.com/everest7/p/10666374.html
Copyright © 2011-2022 走看看