Java 封装jdbc查询

来源:互联网 发布:新媒体排版软件 编辑:程序博客网 时间:2024/05/29 12:22
----------根据sql和条件-----------package fozzz;import java.util.Vector;public class myTest {    public static void main(String[] args) {        // TODO Auto-generated method stub        //sql语句        String sql = "select sc.sno,s.sname,sc.grade from student s " + "INNER JOIN sc on s.sno=sc.sno "                + "INNER JOIN course c on c.courseid=sc.courseid " + "where c.cname=? and sc.grade>?";        // 参数        Vector<Object> vector = new Vector<Object>();        vector.add("取经");        vector.add(40);        //得到结果        Select select = new Select(sql, vector);        Vector<Vector<Object>> result = select.getResult();        System.out.println(result);    }}
-----------连接工厂----------package util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class MyConnection {    public Connection getConnection() {        Connection connection = null;        try {            connection = DriverManager.getConnection("jdbc:mysql://192.168.1.199/my", "root", "root");        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return connection;    }}
----------连接数据库-----------package fozzz;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Vector;import util.MyConnection;public class Select {    private Vector<Vector<Object>> result;    public Select(String sql, Vector<Object> vector2) {        int member = sql.split(" ")[1].split(",").length;        Connection connection = new MyConnection().getConnection();        try {            PreparedStatement prepareStatement = connection.prepareStatement(sql);            // prepareStatement.setObject(0, "1");            for (int i = 0; i < vector2.size(); i++) {                prepareStatement.setObject(i + 1, vector2.get(i));            }            ResultSet rs = prepareStatement.executeQuery();            result = new Vector<Vector<Object>>();            while (rs.next()) {                Vector<Object> vector = new Vector<>();                for (int j = 0; j < member; j++) {                    vector.add(rs.getObject(1 + j));                }                result.add(vector);            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            try {                connection.close();            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }    public Vector<Vector<Object>> getResult() {        return result;    }}
0 0
原创粉丝点击