首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >使用正则表达式来提取出sql语句中where的值

使用正则表达式来提取出sql语句中where的值

作者头像
贺公子之数据科学与艺术
发布2025-08-29 16:49:48
发布2025-08-29 16:49:48
1500
举报
使用正则表达式来提取出sql语句中where的值。下面是一个示例代码:
代码语言:javascript
复制
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\'']

下面是一个使用Python编写的SQL语句执行通用类的示例代码:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-08-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用正则表达式来提取出sql语句中where的值。下面是一个示例代码:
  • 下面是一个使用Python编写的SQL语句执行通用类的示例代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档