87 lines
2.8 KiB
Python
87 lines
2.8 KiB
Python
import pymysql
|
||
|
||
|
||
# ==============================数据库模块===================================
|
||
def check_link_exists(host, user, password, database, link):
|
||
"""
|
||
检查指定的 link 是否存在于 MySQL 数据库表中,如果不存在,则插入该链接
|
||
:param host: MySQL 数据库主机地址
|
||
:param user: MySQL 用户名
|
||
:param password: MySQL 密码
|
||
:param database: 数据库名称
|
||
:param link: 需要检查的链接
|
||
:return: 如果链接存在,返回 True;如果链接不存在且插入成功,返回 False
|
||
"""
|
||
connection = None # 确保 connection 被初始化
|
||
|
||
try:
|
||
# 连接到 MySQL 数据库
|
||
connection = pymysql.connect(
|
||
host=host,
|
||
user=user,
|
||
password=password,
|
||
database=database
|
||
)
|
||
|
||
with connection.cursor() as cursor:
|
||
# 查询链接是否存在
|
||
cursor.execute("SELECT 1 FROM links WHERE link = %s", (link,))
|
||
result = cursor.fetchone()
|
||
|
||
# 如果链接存在
|
||
if result:
|
||
return True
|
||
else:
|
||
return False
|
||
|
||
except pymysql.MySQLError as e:
|
||
print(f"数据库错误: {e}")
|
||
return False
|
||
finally:
|
||
# 确保在结束时关闭连接
|
||
if connection:
|
||
connection.close()
|
||
|
||
|
||
def check_link_insert(host, user, password, database, link):
|
||
"""
|
||
检查指定的 link 是否存在于 MySQL 数据库表中,如果不存在,则插入该链接
|
||
:param host: MySQL 数据库主机地址
|
||
:param user: MySQL 用户名
|
||
:param password: MySQL 密码
|
||
:param database: 数据库名称
|
||
:param link: 需要检查的链接
|
||
:return: 如果链接存在,返回 True;如果链接不存在且插入成功,返回 False
|
||
"""
|
||
connection = None # 确保 connection 被初始化
|
||
try:
|
||
# 连接到 MySQL 数据库
|
||
connection = pymysql.connect(
|
||
host=host,
|
||
user=user,
|
||
password=password,
|
||
database=database
|
||
)
|
||
|
||
with connection.cursor() as cursor:
|
||
# 查询链接是否存在
|
||
cursor.execute("SELECT 1 FROM links WHERE link = %s", (link,))
|
||
result = cursor.fetchone()
|
||
if result:
|
||
# 如果链接已经存在,返回 True
|
||
return True
|
||
else:
|
||
# 插入链接
|
||
cursor.execute("INSERT INTO links (link) VALUES (%s)", (link,))
|
||
connection.commit() # 提交事务
|
||
print("链接已插入")
|
||
return False
|
||
except pymysql.MySQLError as e:
|
||
print(f"数据库错误: {e}")
|
||
return False
|
||
finally:
|
||
# 确保在结束时关闭连接
|
||
if connection:
|
||
connection.close()
|
||
|