0

how can i replace hardcoded number with variable in this java statement which is accessing the mysql datatabase using jdbc. the query is executed using executeQuery(query)

here is the java statement

String query = "select * from TableA where num = '1233' ";

i need to replace this 1233 with a variable in this statement.

any help appreciated

Regards,

2 Answers 2

7

If you can use prepared statement, you'll be safer (no risk of SQL injection):

    Connection con = getMyConnection();
    try {
        PreparedStatement ps = con.prepareStatement("select * from TableA where num = ?");
        try {
            ps.setLong(1, number);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                //TODO
            }
        } finally {
            ps.close();
        }
    } finally {
        con.close();
    }
Sign up to request clarification or add additional context in comments.

4 Comments

@OP: Using a PreparedStatement like this solves a number of issues for you (escaping special characters in strings, formatting timestamps correctly, etc.), definitely the way to go. Also, you can re-use PreparedStatement instances if you need to (in a loop, for instance).
In addition to being safer, the driver or the pool implementation may use a query cache that improves performance.
what if the statement is not executeQuery(query) but executeUpdate(query) example query = " create view view1 as select * from table where num = '1233'";
Same thing. Read the documentation.
0

Are you using Hibernate? If yes this is how you should go supose str is the string/integer you want to replace then get the str by requestobject and continue by using the following code.

try {
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
session = sessionfactory.openSession();<br>
String query = "from Contact c where name='"+str+"'";
Query query1 = session.createQuery(query);<br>
list = query1.list();
System.out.println("Number of users in the system :- "+list.size());
for (Contact contact : list) {
System.out.println(contact.getId()+" : "+contact.getName()+" : "+ contact.getRole()+ " : "+ contact.isEnable());
}

1 Comment

Even with Hibernate, you should use query parameters. In Hibernate it's achieved via the org.hibernate.Query's set* methods, which is later translated by Hibernate to a PreparedStatement. See Jerome's answer for all the reasons why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.