jdbc——简单的查询操作

来源:互联网 发布:mac 网盘 知乎 编辑:程序博客网 时间:2024/06/05 12:00
public class SelectProcess {
    public static void main(String[] args) {
        //设置执行操作语句
        String sql = "select * from tbl_user";
        Connection conn = null;                //代表当前数据库连接
        Statement statement = null;            //数据库发送sql语句
        ResultSet resultset = null;            //代表结果集,封装了从数据库得到的数据

        try {

            //加载驱动

            Class.forName("com.mysql.jdbc.Driver");

            //打开连接

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "******");   //三个参数分别是数据库地址、数据库登录账号及密码

            statement = conn.createStatement();

            //执行操作

            resultset = statement.executeQuery(sql);
            while(resultset.next()){
                System.out.print(resultset.getInt("id")+" ");
                System.out.print(resultset.getString("name")+" ");
                System.out.print(resultset.getString("password")+" ");
                System.out.print(resultset.getString("email")+" ");
                System.out.println();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                resultset.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
0 0
原创粉丝点击