数据库是一个共享的硬盘,可以多人同时地进行访问、更改数据。为了方便存储与多人访问,将实体数据存放在mysql数据库中。
处理好的实体数据一直以jsonline的格式进行的存储,组内之间数据共享时,数据传输过于笨重,所以将实体数据存放在Mysql中,方便多人共同访问。
主要分为pymysql的下载、数据库的创建、数据的增删改查。数据库运维已经在服务器上安装好。
使用pip install 命令即可,安装完之后导入pymysql。
pip install pymysql
import pymsql
import jsonlines
db = pymysql.connect(host='xxx.mysql.xxx.com',
user='user_name',
password='password',
database='user_database')
在指定的database下创建了表名为'ENRIRY_INFO_TABLE'的数据表。并指定了表内容,指定数据类型ENTITY_ID为主键。
import pymsql
db = pymysql.connect(host='xxx.mysql.xxx.com',
user='user_name',
password='password',
database='user_database')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
create_basic_table_sql = """
CREATE TABLE IF NOT EXISTS ENRIRY_INFO_TABLE(
ENTITY_ID CHAR(50) NOT NULL,
ENTIYT_NAME CHAR(50),
ENTITY_BASCINFO CHAR(50),
ENTITY_SUMMARY CHAR(50),
ENTITY_ORDER INT,
ENTITY_LABEL CHAR(50),
)"""
status = cursor.execute(create_basic_table_sql)
print("status: ", status)
def get_entity_value():
entity_id = '4420182'
entity_name = '北京五棵松体育中心棒球场'
entity_desc = '北京市海淀区棒球场'
entity_summary ='北京五棵松体育中心棒球场是2008年北京奥运会的棒球项目的临时比赛场馆'
entity_order = 0
entity_label = '体育'
return "VALUES({entity_id},{entity_name},{entity_desc},{entity_summary},{entity_order},{entity_label})".format(entity_id = '\''+ str(entity_id) +'\'' ,entity_name = '\'' + str(entity_name)+'\'',entity_desc = '\'' + str(entity_desc)+'\'',entity_summary ='\'' + str(entity_summary)+'\'' ,entity_order = entity_order,entity_label = '\''+ str(entity_label)+'\'')
def write_entity_inforamtion(db,information):
#创建游标
cursor = db.cursor()
try:
insert_basic_table_sql = "INSERT INTO ENRIRY_INFO_TABLE (ENTITY_ID,
ENTIYT_NAME,ENTITY_BASCINFO,ENTITY_SUMMARY,ENTITY_ORDER,ENTITY_LABEL)" + information
#执行
cursor.execute(insert_basic_table_sql)
#提交
db.commit()
except Exception as e :
#回滚
db.rollback()
information = get_entity_value()
write_entity_inforamtion(db,information)
# 写入完成后,关闭数据库连接
db.close()
def serach(db):
cursor = db.cursor()
search_basic_sql = """SELECT * FROM ENRIRY_INFO_TABLE LIMIT 100"""
cursor.execute(search_basic_sql)
# 获取所有记录列表
results = cursor.fetchall()
return results
search_result = search(db)
# 查询完成后,关闭数据库连接
db.close()
def update_inforamtion(db):
#创建游标
cursor = db.cursor()
try:
update_basic_table_sql = f"update ENRIRY_INFO_TABLE set ENTIYT_NAME ='五棵松' where entity_id = '4420182';"
#执行
cursor.execute(update_basic_table_sql)
#提交
db.commit()
except Exception as e :
#回滚
db.rollback()
def delete_inforamtion(db):
#创建游标
cursor = db.cursor()
try:
delete_basic_table_sql = f"delete from ENRIRY_INFO_TABLE where entity_id = '4420182';"
#执行
cursor.execute(update_basic_table_sql)
#提交
db.commit()
except Exception as e :
#回滚
db.rollback()
reference:python操作mysql数据库_是佳佳呀~的博客-CSDN博客_python mysql