Web应用开发连接数据库并拉出数据1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192/** * */package cn.edu.nsu.infoSubSys.db.demo;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;/** * @author Pu_Junming * */public class UsersDAO { // 全局数据定义(属性.成员变量定义) private Connection connection; private PreparedStatement pst; private ResultSet rst; // 处理数据(方法【构造方法 + 行为方法】) public UsersDAO() { } public UsersDAO(Connection connection,PreparedStatement pst,ResultSet rst) { this.connection = connection; this.pst = pst; this.rst = rst; } // 行为方法 public void selectById(int id) throws ClassNotFoundException, SQLException { // 加载JDBC驱动 Class.forName("com.mysql.cj.jdbc.Driver"); // 获得数据库连接 connection = DriverManager.getConnection("jdbc:mysql://172.17.130.84:3306/infosubsysdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false", "root", "pujunming5893"); // 封装SQL语句 String sql = "SELECT * FROM users WHERE users_id=?"; pst = connection.prepareStatement(sql); // 参数绑定 pst.setObject(1, id); // 执行AQL rst = pst.executeQuery(); // 处理执行结果 // next() 判断有没有下一条记录,如果有返回true,进入下一条记录,false则直接退出 ResultSetMetaData resultSetMetaData= rst.getMetaData(); while (rst.next()) { // 获取列标签 for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) { String columnLabel = resultSetMetaData.getColumnLabel(i+1); Object object = rst.getObject(columnLabel); System.out.print(object + "\t"); } System.out.println(); } // 关闭数据库连接 if (rst != null) { rst.close(); } if (connection != null) { connection.close(); } if (pst != null) { pst.close(); } // } /** * @param args * @throws SQLException * @throws ClassNotFoundException */ public static void main(String[] args){ // TODO Auto-generated method stub UsersDAO usersDAO = new UsersDAO(); try { usersDAO.selectById(1); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}