使用数据库响应java中的get请求

时间:2011-02-27 12:16:59

标签: java mysql

我正在尝试使用数据库响应java中的get请求。但它会抛出一些错误,我不知道如何修复它。

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, HttpServletResponse 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());
        }
    }
}

如果我在主方法中设置了doGet代码块,那么一切都很好吗?我是Java的新手帮忙!

编辑:

例外是“com.mysql.jdbc.Driver”;

1 个答案:

答案 0 :(得分:0)

使用catch块中的e.printStackTrace();打印出完整的堆栈跟踪。

您的类路径中可能没有包含com.mysql.jdbc.Driver的mysql-connector jar。使用以下方法打印出来检查您的类路径:

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