配置连接池,连接数据库,展示Jsp中MySQL数据库中的一张表的内容
JSP页面代码
package com;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class connect {
public Connection conn;
public Statement st;
public ResultSet rs;
public Connection getConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/like", "root", "447996694");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public List getList(){
List list = new ArrayList();
String sql = "select name,sex,age,tel from students";
conn = getConn();
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
list.add(rs.getString("name"));
list.add(rs.getString("sex"));
list.add(rs.getString("age"));
list.add(rs.getString("tel"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args){
connect wade = new connect();
List list = wade.getList();
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
后台代码
package com;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class connect {
public Connection conn;
public Statement st;
public ResultSet rs;
public Connection getConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/like", "root", "447996694");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public List getList(){
List list = new ArrayList();
String sql = "select name,sex,age,tel from students";
conn = getConn();
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
list.add(rs.getString("name"));
list.add(rs.getString("sex"));
list.add(rs.getString("age"));
list.add(rs.getString("tel"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args){
connect wade = new connect();
List list = wade.getList();
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
数据库表结构
运行结果