python将数据写入表错误

时间:2017-06-08 10:17:04

标签: python mysql

编写python程序创建一个mysql表并将数据插入此表,程序如下:

def pre_data_db_manage(type,data):
    conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="********", db="facebook_info",charset="utf8")
    cur = conn.cursor()


    if type == "pre_davi_group_members_data":
        is_exist_table_sql = "SHOW TABLES LIKE 'fb_pre_davi_group_members_posts'"
        if cur.execute(is_exist_table_sql) == 0:
        create_table_sql = '''CREATE TABLE fb_pre_davi_group_members_posts (id bigint not null primary key auto_increment,userID bigint,userName varchar(128),userURL varchar(256),
                                    postTime varchar(128),postText text,postTextLength int,likesCount int,sharesCount int,commentsCount int,postTextPolarity varchar(64),postTextSubjectivity varchar(64))'''
        cur.execute(create_table_sql)

    r = re.compile(r'^[a-zA-Z0-9]')
    for item in data:
        if "'" in item["PostText"]:
            item["PostText"] = item["PostText"].replace("'"," ")
        if "\\" in item["PostText"]:
            item["PostText"] = item["PostText"].replace("\\","\\\\")
        for i in item["PostText"]:
            result = r.match(i)
            if result == None:
                print("in re")
                item['PostText'] = item['PostText'].replace(i, ' ')
        if "nan" in item["SharesCount"]:
            item["SharesCount"] = 0
        if "nan" in item["LikesCount"]:
            item["LikesCount"] = 0
        if "nan" in item["CommentsCount"]:
            item["CommentsCount"] = 0
        if "nan" in item["PostTextLength"]:
            item["PostTextLength"] = 0
        item["PostTextLength"] = int(item["PostTextLength"])
        item["LikesCount"] = int(item["LikesCount"])
        item["SharesCount"] = int(item["SharesCount"])
        item["CommentsCount"] = int(item["CommentsCount"])

        if type == "pre_davi_group_members_data":
            insert_sql = '''INSERT INTO fb_pre_davi_group_members_posts (userID,userName,userURL,
                        postTime,postText,postTextLength,likesCount,sharesCount,commentsCount,postTextPolarity,postTextSubjectivity) VALUES
                        ({0},"{1}",'{2}','{3}','{4}',{5},{6},{7},{8},{9},{10})'''.format(item["UserID"],item["UserName"],item["UserURL"],item["PostTime"],item["PostText"],item["PostTextLength"],item["LikesCount"],item["SharesCount"],item["CommentsCount"],item["PostTextPolarity"],item["PostTextSubjectivity"])
            print(insert_sql)
            try:
                cur.execute(insert_sql)
            except Exception as e:
                print("insert error")
                continue
    cur.close()
    conn.commit()
    conn.close()

并编写如下调用语句:

type = "pre_davi_group_members_data"
pre_data_db_manage(type, df_list)

但是,执行此程序时,发现没有数据插入到表中:fb_pre_davi_group_members_posts,

在mysql命令行中,写:

select count(*) from fb_pre_davi_group_members_posts;

结果是0

你可以告诉我原因以及如何解决它

0 个答案:

没有答案