zoukankan      html  css  js  c++  java
  • Python 操作MySQL数据库

    • 环境

    Anaconda3 Python 3.6, Window 64bit

    • 目的

    从MySQL数据库读取目标表数据,并处理

    • 代码
    # -*- coding: utf-8 -*-
    
    import pymysql
    
    
    # 配置数据库连接
    dbconn=pymysql.connect(
        host="***",
        database="kimbo",
        user="kimbo_test",
        password="***",
        port=3306,
        charset='utf8'
     )
         
    # 使用cursor()方法获取操作游标 
    cursor = dbconn.cursor()
    
    # 配置执行语句
    sqlcmd1="drop table if exists zss_test;" 
            "create table zss_test(" 
            "ID bigint not null comment 'ID'," 
            "col_name varchar(100) comment '列名'," 
            "col_type varchar(100) comment '数据类型'," 
            "update_time timestamp not null default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment '更新时间');"
    
    
    sqlcmd2="truncate table zss_test;insert into zss_test(id,col_name,col_type) VALUES (1,'star_type','string'),(2,'cust_type','string');"
    
    try:
        # 执行sql语句
        cursor.execute(sqlcmd1)
        cursor.execute(sqlcmd2)
        dbconn.commit()
    except:
        # Rollback in case there is any error
       dbconn.rollback()
    
    #获得表中总记录数
    res=cursor.execute("select * from zss_test")
    print('总记录数:%d' % res +' 条。')
    
    print("分别为--------->")
    #打印表中的多条数据
    # 使用 fetchone() 方法获取一条。
    # 使用 fetchall() 方法获取全部
    info=cursor.fetchall()
    for i in info:
        print(i)
    
    # 关闭游标,关闭数据库连接
    cursor.close()
    dbconn.close()
    

    结果如图:

  • 相关阅读:
    python appium环境搭建
    github 删除某个文件
    python 导入的模块使用了相对路径,导致找不到文件错误
    python asyncio协程
    python 获取调用函数的名字和行号
    monkey测试命令
    python 属性查询顺序,数据描述符
    JS各循环的差别
    AngularJS复习小结
    那些不正经的前端笔试题
  • 原文地址:https://www.cnblogs.com/kimbo/p/6535123.html
Copyright © 2011-2022 走看看