Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

accessing database inside java code

 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am having a database connection string in a code as follows:



I need to access this code and need to execute queries wherever i want in the following code:



please assist me to do this.I am writing connection string in each and every place in my code now.this causes too many connections problem in mysql.

Thanks
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should move the DB code out of the main method into its own method that has suitable parameters. Maybe

public ResultSet runQuery (String query)

would be a good choice (assuming that running a query and obtaining the result is what you want to do).
 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.I have removed the main method and modified as you said as follows:


It displays the error:

This method must return a result of type ResultSet


Am i wrong here?
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, right now the code doesn't return a ResultSet; it opens and closes a DB connection, which by itself is not a very useful thing to do. Like I said, I assumed that you want to use this code to run DB queries. If you intended to do something else, let us know what that is.
 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes.you are correct. i want to use this code to run DB queries in different java codes.How can i return a ResultSet?
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thinking about this, what I suggested earlier is actually not going to work, because you can't return a ResultSet if the underlying DB connection is closed. So you may want to keep the connection as an instance field, and then have methods like

public boolean connect()

public ResultSet query (String query)

public boolean disconnect()

The "boolean" result is so that the methods can report success/failure. It's very important to always close DB connections once the code is done with them.

The Sun Java Tutorial has an extensive chapter on JDBC, and many code examples can be found here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic