This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I am creating a Java connection to a MySQL database and I have several different classes which will be utilizing that connection for various purposes. This will involve different MySQL user accounts where the user logs in to the database and performs the necessary actions.
So, I guess my question is: Is there a way to create a Connection class for a persistent connection to the database, so long as a specified user is logged into the system, that can be reused in other classes for authentication? If so, how can I use
If I am trying to go about this all wrong then let me know that as well.
Any help would be very....Helpful!
Thanks, Bryan
Bryan Scarbrough<br /> <br />Consistency is the last resort of the unimaginative!
A connection is tied to a user. While you can keep open a connection and pass it around to different classes, it will always be for that specific user. For a different user, you have to open a new connection.
Is there a way to place the following in its own class:
I am trying to prevent placing this into every file class that I am using for queries.
Thanks for your reply. Hope this is a little more clear.
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35439
9
posted
0
You can make it a static method in some utility class. That way you can access it from everywhere. The Class.forName().getInstance() only needs to be done once - you don't need to repeat it for every connection.
Bryan Scarbrough
Ranch Hand
Joined: Aug 08, 2005
Posts: 49
posted
0
Once I set it up as a method to a utility class, then how can I reuse that information? Is there a way I can return the result set and then utilize that for creating statements, etc? If so, how?
I have been working on this for a couple of days now and more hours than I care to admit and I am completely lost at this point!
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35439
9
posted
0
It would go something like this: In Helperclass.java you would have:
Connection con = Helperclass.getConnection(url, user, password); // do something with con; of course, it could be null!
If the URL is always the same (i.e., you're using the same DB all the time), you could have the helper class take care of that as well. [ August 09, 2005: Message edited by: Ulf Dittmer ]