Web应用开发

连接数据库并拉出数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
*
*/
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();
}

}

}