python脚本读取数据库

import json
import pymysql
import csv
#mysql的数据库连接信息
conn = pymysql.connect(
    #服务器地址
        host = '127.0.0.1',
    #端口号
        port = 3306,
    #用户名
        user = 'root',
    #密码
        passwd = 'admin',
    #数据库名称
        db = 'tencent_demo',
    #字符编码格式
        charset = 'utf8',
    )
#设置游标,进行数据库操作
cursor = conn.cursor()
#创建表语句
# sql = "CREATE TABLE Student(name CHAR(9),gender CHAR(20))"
# cur.execute(sql)
#json文件读取路径
# path1 = "E:/机器学习实验/实验2/Demo/data.txt"



with open("test3.csv","a",newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=' ')
    writer.writerow(["原始数据","feature1","feature2"])

    # SQL 查询语句
    name = "qwe"
    date = "2021-07-18"

 
    sql = "select series,sample_id from sample_series where name = ? and date = ? "
    try:
        # 执行SQL语句
        cursor.execute(sql,name,date)
        # 获取所有记录列表
        results = cursor.fetchall()
        series = results[0][0]
        sample_id = results[0][1]
        print(series,sample_id)
    except:
        print("Error: unable to fecth data")

    sql = "select type from sample where id = ?"
    try:
        # 执行SQL语句
        cursor.execute(sql,sample_id)
        # 获取所有记录列表
        results = cursor.fetchall()
        type = results[0][0]
        print(type)
    except:
        print("Error: unable to fecth data")

    sql = "select good,miss,doubt from mark where name = ? and sample_id = ?"
    try:
        # 执行SQL语句
        cursor.execute(sql, name,sample_id)
        # 获取所有记录列表
        results = cursor.fetchall()
        good = results[0][0]
        miss = results[0][1]
        doubt = results[0][2]

        print(good,miss,doubt)

    except:
        print("Error: unable to fecth data")




    # 关闭数据库连接
cursor.close()
conn.close()














版权声明:本文为weixin_45532227原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。