JSP动态查询数据库
使用JSP结合servlet动态查询数据库,并展示!
项目示意图:
使用Properties配置文件进行读入读出,可以做到不妨碍程序运行修改数据库配置数据。
即在src源文件夹下创建*.properties后缀文件,也可以创建与src平级的resources文件 文件类型 source Folder,把properties配置文件放入其中:
此次演示使用的是MySQL数据库,故DBInfo.properties内存放的数据如下
drive=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaTest?useSSL=false&serverTimezone=UTC
user=root
password=tiger
url中?前的javaTest是此次演示的数据库名称,读者需要配置成自己的数据库
编写数据库连接工具类
此工具类具有读取properties配置文件的功能
package com.db.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DBConn {
private static String DRIVE;
private static String URL;
private static String USER;
private static String PWD;
//由于读取配置文件和获取驱动class类只需要一次,故放入静态代码块中
//在程序加载时就自动编译一次永久使用。
static{
//读取配置文件
Properties properties=new Properties();
InputStreamin=Thread.currentThread().getContextClassLoader().getResourceAsStream("DBInfo.properties");
try {
properties.load(in);
//将读取到的配置文件内的数据赋值给类
DRIVE=properties.getProperty("drive");
URL=properties.getProperty("url");
USER=properties.getProperty("user");
PWD=properties.getProperty("password");
//获取驱动的class类对象
Class.forName(DRIVE);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取数据库连接的方法
public static Connection getConnection(){
Connection conn=null;
try {
conn=DriverManager.getConnection(URL,USER,PWD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭数据库连接的方法
public static void closeDB(Connection connection,Statement statement,ResultSet resultSet){
try {
if(resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
connection=null;
statement=null;
resultSet=null;
}
}
}
所用到的数据库相关数据:
t_class数据库
t_student数据库
表内容请自定
与t_class表对应的T_class类
package com.db.utils;
public class T_class {
private int cno;
private String cname;
private String caddr;
public int getCno() {
return cno;
}
public void setCno(int cno) {
this.cno = cno;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCaddr() {
return caddr;
}
public void setCaddr(String caddr) {
this.caddr = caddr;
}
public T_class(int cno, String cname, String caddr) {
super();
this.cno = cno;
this.cname = cname;
this.caddr = caddr;
}
public T_class() {
super();
}
@Override
public String toString() {
return "T_class [cno=" + cno +