aspose file tools*
The moose likes JDBC and the fly likes JDBC / Servlet / MySQL Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "JDBC / Servlet / MySQL" Watch "JDBC / Servlet / MySQL" New topic
Author

JDBC / Servlet / MySQL

martin weber
Greenhorn

Joined: Jul 22, 2008
Posts: 3
Hi everyone, I have problems reading data from a MySQL-Database through a Servlet. The Connection works; it must be a simple step.
I don't know how to do the last step. The ContextListener checks the Connection at startup. Heres my Code:

ContextListener.java




context.xml




Response.java

Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18987
    
    8

If I am not mistaken, your question is "How can I get something (a Connection) out of the ServletContext in a servlet?" Well, this is hardly a JDBC question, so perhaps I didn't understand your problem.

So, let me suggest that in your servlet you shouldn't be importing any com.mysql classes. Just like in your context listener, you should be importing those classes from the java.sql package instead.

Also, in web applications which are going to have more than one user, it is not a good idea to have only a single Connection available to those users. Typically you configure a connection pool and have the servlet get a connection from the pool. But I see your code is a demo, so perhaps you planned to do that later.
martin weber
Greenhorn

Joined: Jul 22, 2008
Posts: 3
Thanks for your answer.
You are right: connection pooling is a further feature, first we want to implement the basics.

I will follow your hint with the com.mysql-Classes, I think this was a mistake trough Eclipse; i clicked the wrong classes to import.

So, I'm sorry if I asked my question wrong; here step by step what I think it has to be (the way I coded it)...

*) I start the servlet. The context-listener starts and checks if the connection works. If it works, the connection is established and works for the whole "underlying" webapp. Right?

*) With the start of the servlet I wan't to get data out the SQL. So I can use the connection provided and established by the context-listener. Right? (Uh, this might be wrong...)

But I don't know how to get access to the DataSource-Object (Is it an object?)



Thanks, guys!
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18987
    
    8

Originally posted by martin weber:
But I don't know how to get access to the DataSource-Object (Is it an object?)
Of course it's an object. It's not a primitive so it must be an object. You put it into the servlet context in your listener class, right? So you take it out of the servlet context in your servlet. Step 1: get the servlet context. Step 2: get the "datasource" attribute from that.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JDBC / Servlet / MySQL