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)    # 将命令和参数分隔开,操作起来更加安全
  • 相关阅读:
    C# DictionaryHelper
    C# Autofac 的 BeanFactory
    正则替换
    java页面表格导出为Excel实现
    CentOS 7 下安装Nginx
    认识Java 虚拟机的架构
    06 查看网卡实时流量
    05 找出占用CPU、内存过高的进程
    04 一键查看服务器资源利用率
    03 批量创建100个用户并设置随机密码
  • 原文地址:https://www.cnblogs.com/everest7/p/10666374.html
Copyright © 2011-2022 走看看