Witam
Utworzyłem sobie zwykłą klasę i napisałem tam kod do łączenia się z bazą. Przetestowałem pod eclipse i wszystko ok. Następnie zrobiłem coś takiego:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
//start
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head><title>Hello World</title></head>");
out.println("<body>");
out.println("<h1>Hello World</h1>");
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String atrybut = req.getParameter("atrybut");
try
{
String userName = "root";
String password = "a123456";
String url = "jdbc:mysql://localhost/users?user="
+ userName
+ "&password="
+ password;
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url);
st=conn.createStatement();
rs=st.executeQuery("select * from users1 WHERE id=2");
while(rs.next())
{
out.println("<p>" + rs.getString(1)+" "+rs.getString("user") +" "+rs.getString(3) +" "+rs.getString(4)+"</p>");
}
out.println ("<p>Database connection established</p>");
out.println("</body></html>");
}
catch (Exception e)
{
out.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
i tu mi wyskakuje tylko oczywiście "Hello World" i "Cannot connect to database server" co robie źle. Może ma ktos jakiś prosty przykład jak wyciągnąć dane z bazy i wyswietlić w servlecie.
PS metoda POST jeszcze nic nie robi :)