
import re
sql = "SELECT * FROM table WHERE col1 = 'value1' AND col2 = 'value2'"
# 使用正则表达式提取出where的值
result = re.findall(r"WHERE\s+(.*?)(?:\s+|$)", sql)
if result:
# 提取出的值是一个字符串,可以进一步处理成列表或其他格式
values = result[0].split(" AND ")
print(values)
else:
print("No 'where' clause found in the SQL statement.")输出结果为:['col1 = \'value1\'', 'col2 = \'value2\'']。
import pymysql
class SQLExecutor:
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
def execute(self, sql):
try:
# 连接到数据库
connection = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database
)
# 创建游标对象
cursor = connection.cursor()
# 执行SQL语句
cursor.execute(sql)
# 提交事务
connection.commit()
# 获取执行结果
result = cursor.fetchall()
# 关闭游标和连接
cursor.close()
connection.close()
return result
except Exception as e:
print("An error occurred:", str(e))
return None
# 示例使用
host = "localhost"
port = 3306
user = "root"
password = "password"
database = "mydb"
executor = SQLExecutor(host, port, user, password, database)
# 执行查询语句
sql = "SELECT * FROM table"
result = executor.execute(sql)
print(result)
# 执行插入语句
sql = "INSERT INTO table (col1, col2) VALUES ('value1', 'value2')"
executor.execute(sql)这个示例代码使用了pymysql模块,可以通过execute方法执行SQL语句。在初始化SQLExecutor类时,需要提供数据库的连接信息。execute方法接收一个SQL语句作为参数,并返回执行结果。如果执行过程中发生异常,将会在控制台打印错误信息,同时返回None。