开发者

Respond to a get request in java using a database

I'm trying to respond to a get request in java using a database. But it throws some error which I don't know a clue how to fix it.

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServl开发者_如何学PythonetResponse resp)
    throws ServletException, IOException{
        try{
            //Accessing driver from the JAR file 
            Class.forName ("com.mysql.jdbc.Driver").newInstance (); 

            //Connect to Clockie's database
            Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/database", "root", "root");

            //Here we create our query
            String sql = "" +
                    "SELECT * " +
                    "FROM profiles " +
                    "WHERE profileId = '27'";
            PreparedStatement statement = con.prepareStatement(sql);

            ResultSet result = statement.executeQuery();
            String xmls = "";

            result.next();
            xmls = result.getString("firstName") + " "+result.getString("lastName");
            System.out.println(xmls);

            resp.getWriter().println(xmls);
        }
        catch(Exception e){
            System.err.println(e.getMessage());
        }
    }
}

Everything is fine though, if I set the doGet code block inside the a main method? I'm new to Java pls help!

EDIT:

the exception is "com.mysql.jdbc.Driver";


Print out the full stack trace using e.printStackTrace(); in your catch block.

You may not have the mysql-connector jar which contains com.mysql.jdbc.Driver on your classpath. Check your classpath by printing it out using:

System.out.println("classpath = " + System.getProperty("java.class.path"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜