forked from lsq960124/Flask-BookRecommend-Mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_data_save_to_mysql.py
190 lines (151 loc) · 7.03 KB
/
read_data_save_to_mysql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 15 00:01:50 2018
@author: Administrator
"""
import pandas as pd
import pymysql
config = {'user': 'root',
'password': '123456',
'port':3300,
'host': '127.0.0.1',
'db': 'Book',
'charset':'utf8'}
class BookSqlTools:
#链接MYSQL数据库
#读取出来转化成pandas的dataframe格式
def LinkMysql(self, sql):
try:
connection = pymysql.connect(user=config['user'],
password=config['password'],
port=config['port'],
host=config['host'],
db=config['db'],
charset=config['charset'])
cur = connection.cursor()
except Exception as e:
print("Mysql link fail:%s" % e)
try:
cur.execute(sql)
except Exception as e:
print("dont do execute sql")
try:
result1 = cur.fetchall()
title1 = [i[0] for i in cur.description]
Main = pd.DataFrame(result1)
Main.columns = title1
except Exception as e:
print(" select Mysql error:{}".format(e))
return Main
#数据库中的表插入数据
def UpdateMysqlTable(self, data, sql_qingli, sql_insert):
try:
connection = pymysql.connect(user=config['user'],
password=config['password'],
port=config['port'],
host=config['host'],
db=config['db'],
charset=config['charset'])
cursor = connection.cursor()
except Exception as e:
print("Mysql link fail:%s" % e)
try:
cursor.execute(sql_qingli)
except:
print("dont do created table sql")
try:
datas = data.to_dict(orient='records')
for data in datas:
x = list(data.values())
sql = sql_insert.format(tuple(x)).encode(encoding='utf-8')
print(sql)
try:
cursor.execute(sql)
except Exception as e:
print("Mysql insert fail%s" % e)
except Exception as e:
connection.rollback()
print("Mysql insert fail%s" % e)
connection.commit()
cursor.close()
connection.close()
connection = pymysql.connect(user=config['user'],
password=config['password'],
port=config['port'],
host=config['host'],
charset=config['charset'])
cur = connection.cursor()
cur.execute('DROP DATABASE if exists Book')
cur.execute('CREATE DATABASE if not exists Book')
connection.commit()
cur.close()
# 创建购物车表
connection = pymysql.connect(user=config['user'],
password=config['password'],
port=config['port'],
host=config['host'],
db=config['db'],
charset=config['charset'])
cur = connection.cursor()
createCartSql = '''CREATE TABLE Cart
(UserID VARCHAR(100) ,
BookID VARCHAR(100) )'''
cur.execute(createCartSql)
connection.commit()
cur.close()
connection.close()
BookInfoInsert = BookSqlTools()
#--------------------------------------------------------------------------
#读取本地的BX-Users.csv文件 在数据库中建一个User表 将User.csv内容插入到数据库中
#--------------------------------------------------------------------------
path = './data/BX-Users.csv'
User = pd.read_csv(path, sep=None, error_bad_lines=False)
createUserSql = '''CREATE TABLE User
(UserID VARCHAR(100) ,
Location VARCHAR(100) ,
Age VARCHAR(100) );'''
UserSql_insert='insert into User (UserID,Location,Age) values {}'
BookInfoInsert.UpdateMysqlTable(User,createUserSql,UserSql_insert)
del User
#--------------------------------------------------------------------------
#读取本地的BX-Books.csv文件 在数据库中建一个Books表 将book.csv内容插入到数据库中
#--------------------------------------------------------------------------
path = './data/BX-Books.csv'
Book = pd.read_csv(path, sep=None, error_bad_lines=False)
createBooksSql =''' CREATE TABLE Books
(BookID VARCHAR(999) ,
BookTitle VARCHAR(999) ,
BookAuthor VARCHAR(999) ,
PubilcationYear VARCHAR(999) ,
Publisher VARCHAR(999) ,
ImageS VARCHAR(999) ,
ImageM VARCHAR(999) ,
ImageL VARCHAR(999));'''
BooksSql_insert='insert into Books (BookID,BookTitle,BookAuthor,PubilcationYear,Publisher,ImageS,ImageM,ImageL) values {}'
BookInfoInsert.UpdateMysqlTable(Book,createBooksSql,BooksSql_insert)
del Book
#--------------------------------------------------------------------------
#读取本地的BX-Book-Ratings文件 在数据库中建一个Bookrating表 将bookrating.csv内容插入到数据库中
#--------------------------------------------------------------------------
path = './data/BX-Book-Ratings.csv'
Rating = pd.read_csv(path, sep=None, error_bad_lines=False)
createBookratingSql = '''CREATE TABLE Bookrating
(UserID VARCHAR(999) ,
BookID VARCHAR(999) ,
Rating VARCHAR(999));'''
BookratingSql_insert='insert into Bookrating (UserID,BookID,Rating) values {}'
BookInfoInsert.UpdateMysqlTable(Rating,createBookratingSql,BookratingSql_insert)
del Rating
#--------------------------------------------------------------------------
#读取本地的Booktuijian.csv文件 在数据库中建一个Booktuijian表 将Booktuijian.csv内容插入到数据库中
#--------------------------------------------------------------------------
Booktuijian = pd.read_csv('data/booktuijian.csv')
Booktuijian['score'] = Booktuijian['score'].apply(lambda x: round(x,2))
Booktuijian['score'] = 10*(Booktuijian['score'])/(max(Booktuijian['score']))
Booktuijian=Booktuijian[['BookID','UserID','score']]
createBookrecomql = '''CREATE TABLE Booktuijian
(UserID VARCHAR(999) ,
BookID VARCHAR(999) ,
score FLOAT(5,3) );'''
BooktuijianSql_insert='insert into Booktuijian (BookID,UserID,score) values {}'
BookInfoInsert.UpdateMysqlTable(Booktuijian,createBookrecomql ,BooktuijianSql_insert)