0

I'm working with MySQL for long time now and I know that I should only open one Connection at one time.

But now I have an other question that I think is not asked yet. If so please don't blame me, because I couldn't find an answer yet.

Every time I run a MySQL-Query or Update I open a new Statement like this:

Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM ...;");
...
st = c.createStatement();
st.executeUpdate("INSERT INTO ...;");
...
st = c.createStatement();
res = st.executeQuery("SELECT * FROM ...;");
...

First of all. Is it possible to create just one Statement for all the Querys and Updates? Like this:

Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM ...;");
...
st.executeUpdate("INSERT INTO ...;");
...
res = st.executeQuery("SELECT * FROM ...;");
...

And the other question I have is, if I have to close these Statements in the end or if Java does this automatically.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Nicola Uetz
  • 848
  • 1
  • 7
  • 25

2 Answers2

1

You can use a Statement for multiple times. It would be inefficient if you create another Statement object each time.

For JDBC 4.0 and earlier (Java 6 and earlier):

  • A Statement is closed when the connection is closed

So if you close your connections you dont have to worry about closing statements. Closing of connections was disscussed here

Community
  • 1
  • 1
Sergei Podlipaev
  • 1,331
  • 1
  • 14
  • 34
0

you can create a method to do the Update/Insert action

public void updateQuery(String query){
...
}

To prevent SQL injection, try to use PreparedStatement

CSK
  • 352
  • 1
  • 6