What is a method to sanitize a SQL query and substitute all parameters with '?' by leveraging regular expressions?

For instance, I am looking to refine these specific queries

SELECT * FROM mytable1 WHERE field1 = 5;
UPDATE mytable1 SET field1 ="data" WHERE field1 = 5;
INSERT INTO mytable1 VALUES("a", "\"b","c" );

The desired outcome would be as follows

SELECT * FROM mytable1 WHERE field1 = ?;
UPDATE mytable1 SET field1=? WHERE field1 = ?;
INSERT INTO mytable1 VALUES(?,?,?);
...

Answer №1

If you prefer working with a 3rd party library instead of using regex, consider using JSQLParser for modifying SQL strings. Below is an example demonstrating how to replace string and long values in various types of statements.

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.util.deparser.ExpressionDeParser;
import net.sf.jsqlparser.util.deparser.SelectDeParser;
import net.sf.jsqlparser.util.deparser.StatementDeParser;

public class TestTest {

    public static void main(String[] args) throws JSQLParserException {
        String sql_1 = "SELECT * FROM mytable1 WHERE field1  = 5;";
        String sql_2 = "UPDATE mytable1 SET field1 ='data' WHERE field1 = 5;";
        String sql_3 = "INSERT INTO mytable1 VALUES('a','b','c' );";

        System.out.println(modify(sql_1));
        System.out.println(modify(sql_2));
        System.out.println(modify(sql_3));
    }
    public static String modify(String sql) throws JSQLParserException{
        StringBuilder buffer = new StringBuilder();
        ExpressionDeParser expressionDeParser = new ExpressionDeParser() {
            @Override
            public void visit(StringValue stringValue) {
                this.getBuffer().append("?");
            }

            @Override
            public void visit(LongValue longValue) {
                this.getBuffer().append("?");
            }
        };
        SelectDeParser selectDeparser = new SelectDeParser(expressionDeParser,buffer );
        expressionDeParser.setSelectVisitor(selectDeparser);
        expressionDeParser.setBuffer(buffer);
        StatementDeParser stmtDeparser = new StatementDeParser(expressionDeParser, selectDeparser, buffer);
        Statement stmt = CCJSqlParserUtil.parse(sql);
        stmt.accept(stmtDeparser);
        return stmtDeparser.getBuffer().toString();
    }
}

// output: 
//SELECT * FROM mytable1 WHERE field1 = ?
//UPDATE mytable1 SET field1 = ? WHERE field1 = ?
//INSERT INTO mytable1 VALUES (?, ?, ?)

For more examples and information, check out the example pages of jsqlparser.

To download the Maven repository or JAR file, click here: mvnrepository

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The use of ExpressJs res.sendFile is not effective following the implementation of middleware

Currently, my focus is on mastering JWT and its implementation in Node.js with Express. I've developed a middleware that aims to authenticate users using a token: app.use(function(req, res, next) { if(req.headers.cookie) { var authentication = req.h ...

MySQL query to retrieve and arrange data from two tables in a specified sequence

I am looking to extract values from two separate tables and present them in a GridView in a specific format. The first table contains estimated income, while the second table consists of actual income. Here is an example of the estimated income table: ...

What steps can be taken to disable the send button once it has been used and then automatically show gratitude?

My website features a contact form, but I noticed that when users press the send button, there is no confirmation message indicating whether the message was successfully sent. This could potentially lead to multiple spam emails being sent to me. How can I ...

Error: The script is not found in the package.json configuration

I encountered the following error while trying to execute npm run dev: Error: Missing script: "dev" Error: Error: To view a list of available scripts, use the command: Error: npm run Here is a list of scripts present in my package.json file: "scripts ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

Storing text data from Quilljs in Laravel 8 database

I am facing an issue with saving Quilljs Editor content to my database. Whenever I try to save it, nothing gets saved. Is there a method to successfully save Quilljs content to the database and also retrieve the data from the database to populate the Quill ...

The issue of elements not appearing seems to be related to the passing of parameters to the state

In my AngularJS application, I have a form where users must input an application number. Upon successful entry, the corresponding data should be displayed below. This data can only be accessed through the scope if passed as a parameter to the current state ...

Using JSON object as an argument in React functional component

Currently, I'm trying to assign a JSON object to a const variable. I've been successful with using vars in the past, like so: {this.props.user.map(function(user){... However, when it comes to stateless consts, I'm encountering some confusi ...

Tips for adding content to several elements at once using jQuery

My HTML structure is as follows : <span class="section2 section4">hello</span> <span class="section1">World</span> <div class="tab" id="tab1"></div> <div class="tab" id="tab2"></div> <div class="tab" id= ...

Attempting to incorporate a hover effect into this piece of JavaScript code

Hello, I've been trying to implement a mouse-over effect into this code but have not had much luck. Any assistance would be greatly appreciated. If you require additional information, please let me know. The issue I am facing is that when I hover ove ...

React app's setTimeout function fails to execute at the designated time specified

I have a function set up in my React app to handle user authentication and signup. The function is supposed to display an alert message saying "Account Created" upon successful signup, and then redirect the user to their profile page after a 1-second delay ...

Animating Chart.js 2 from right to left instead of from top to bottom

Here is the issue demonstrated in the jsfiddle below. Initially, the data inserts work well. However, when the data set reaches a cap of 10, an unwanted behavior occurs where the data points are animated top-down instead of moving leftward. This can be qu ...

Using JQuery to properly introduce a script in the body of a webpage

<script> /* adjust #splash-bg height based on #meat element */ $(window).on('load',function(){ var splashbgHeight = $("#meat").css("top"); $("#splash-bg").css("height",splashbgHeight); $(w ...

Can establishing relationships between tables in a database improve the speed of query performance?

When incorporating JOIN in my queries, I am curious to understand how the relationships between database tables impact query performance. Can having connected tables lead to improved performance? Appreciate your insights. ...

Invoke callback function to manage modal visibility

My project includes a modal for displaying a login/register form. The default behavior is that the modal opens when triggered by another component using the props show. This setup works perfectly when the modal is called by this specific component. Furthe ...

Encountered an issue while setting up or removing MySQL on Lion

Greetings to all, I am new here and feeling a bit embarrassed about my current situation. I have been struggling with the installation of MySQL on my fresh Macbook Air. After what I thought was a successful installation, I couldn't get it to function ...

The Bootstrap4 nav-tabs are mistakenly causing the entire page to change instead of just the tab content

After encountering an issue on my Angular site while trying to incorporate a bootstrap nav-tab element, I decided to refer to some example code from the official Bootstrap documentation here. The problem arose when clicking on the tabs of my page resulted ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

In production mode, the Angular/JS Express app is stuck in an endless routing loop, while it functions perfectly in development mode

My webapp is constructed using generator-angular-fullstack. While it functions properly in development mode (grunt serve), I encounter a problem with what appears to be an endless routing loop when switching to production mode (grunt serve:dist). The outp ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...