如何使用createQuery()方法创建JDBC连接,使用sql2o?

时间:2016-04-01 15:22:02

标签: java servlets jdbc import sql2o

createQuery()方法需要转换为Connection对象,但似乎此方法可以在SQL2o对象上工作,因为它在包中.... 我正在使用sql2o来创建我的数据库连接;但是,我不明白为什么要使用.createQuery()方法强制转换为Connection对象?

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;

    import java.util.ArrayList;

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

   import org.sql2o.Sql2o;

   import com.google.gson.Gson;
   import com.models.Person;
   import com.tools.DBUtil;
   import com.tools.DataTable;



   /**
    * Servlet implementation class SalesTeam
    */
    @WebServlet(name = "SalesTeam_Table", urlPatterns = {                   "/json/table/salesteam" })
    public class Table_SalesTeam extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Table_SalesTeam() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse    response)
            throws ServletException, IOException {

        // Creating an arraylist based on the Person model in com.models
        ArrayList<Person> people = new ArrayList<Person>();
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;


        String DB_URL = "jdbc:mysql://localhost:3306/salesteam";
        String USER = "root";
        String PASS = "1234 ";
        Sql2o sql2o = new Sql2o(DB_URL, USER, PASS);

        String sql =
                "SELECT empID, fName " +
                "FROM salesteam " +
                "WHERE empID = 1";


    //issue is here...
        try (Connection con = sql2o.open()){
                people = con.createQuery(sql).executeAndFetch(Person.class);

     ////////////////////////

            //Selecting every record in sales_team table
            //pst = conn.prepareStatement("select f_Name, l_Name, email,           contactNum from sales_team ORDER BY f_Name ASC "); 
            //rs = pst.executeQuery();
            while (rs.next()) {
                //Create a person object and fill fields
                Person p = new Person();
                p.setfName(rs.getString("f_Name"));
                p.setlName(rs.getString("l_Name"));
                p.setEmail(rs.getString("email"));
                p.setContact(rs.getString("contactNum"));

                //Add person to people array list
                people.add(p);
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }finally {
            //Must close the database objects
            DBUtil.close(conn, pst, rs);
        }

        //Gson Library was added to WEB-INF/lib
        //Creating a new gson object to hold json
        Gson gson = new Gson();

        //Create a custom DataTable object that takes an ArrayList<Object> and   makes an object
        //Used to create correct datatable json formatting
        DataTable table = new DataTable();
        table.setData(people);

        //Creating string by converting people arraylist to json string with gson object
        //Read up on gson library for json at http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
        String json = gson.toJson(table);

        //Uncomment line below and look in console for what json looks like
        System.out.println(json);

        //Write json string to response
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse                 response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

   }

2 个答案:

答案 0 :(得分:2)

仔细阅读Javadoc。 table{ border-collapse: collapse; } 会返回sql2o#open(),但不会从org.sql2o.Connection继承。如果需要基础JDBC Connection对象,则必须调用java.sql.Connection

似乎sql2o落后于时代,因为更新的JDBC API包含方法(org.sql2o.Connection#getJdbcConnection()Wrapper#unwrap()),以简化JDBC类的自定义实现的使用。

答案 1 :(得分:2)

您的代码是普通的jdbc和sql2o代码的混合。使用sql2o时,不应从ResultSet手动读取。实际上,当您尝试从ResultSet读取时,您的代码会抛出NullPointerException。

它不编译的原因是因为你导入了java.sql.Connection,而Sql2o.open()方法返回了一个org.sql2o.Connection。如果您只删除每个引用的JDBC类,我认为对您来说会更容易。

您的方法应该如下所示(记得删除所有JDBC类的导入):

protected void doGet(HttpServletRequest request, HttpServletResponse    response)
            throws ServletException, IOException {

        String DB_URL = "jdbc:mysql://localhost:3306/salesteam";
        String USER = "root";
        String PASS = "1234 ";
        Sql2o sql2o = new Sql2o(DB_URL, USER, PASS);

        String sql =
                "SELECT empID, fName " +
                "FROM salesteam " +
                "WHERE empID = 1";

        List<Person> people;
        try (Connection con = sql2o.open()){
                people = con.createQuery(sql).executeAndFetch(Person.class);
        }

        // code to generate json here...
    }