aspose file tools*
The moose likes JDBC and the fly likes accessing database inside java code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "accessing database inside java code" Watch "accessing database inside java code" New topic
Author

accessing database inside java code

preethi Ayyappan
Ranch Hand

Joined: Oct 04, 2007
Posts: 518
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
Marshal

Joined: Mar 22, 2005
Posts: 42649
    
  65
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).


Ping & DNS - my free Android networking tools app
preethi Ayyappan
Ranch Hand

Joined: Oct 04, 2007
Posts: 518
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
Marshal

Joined: Mar 22, 2005
Posts: 42649
    
  65
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

Joined: Oct 04, 2007
Posts: 518
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
Marshal

Joined: Mar 22, 2005
Posts: 42649
    
  65
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: accessing database inside java code