读取数据库的数据,通过JavaBean将数据以表格或其他形式呈现到网页,并且可以对其进行增删改的操作,以及数据修改之后网页之间的切换,同时数据库中的数据也需要被正确修改。
1、“SQLHelper.java”
package dbutil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class SQLHelper {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/XXX", user = "XXX", pwd = "XXX"; //XXX的地方需根据实际情况进行修改
private static Connection conn=null;
static {
try {
Class.forName(driver);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void closeConnection(){
try {
if(conn!=null && !conn.isClosed())
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static List<Object[]> executeQueryList(String sql){
List<Object[]> list=new ArrayList<Object[]>();
ResultSet rs=null;
try {
conn = DriverManager.getConnection(url, user, pwd);
Statement cmd = conn.createStatement();
rs=cmd.executeQuery(sql);
ResultSetMetaData metaRs= rs.getMetaData();//元数据
int colsNum=metaRs.getColumnCount();
while(rs.next()){
Object[] arr=new Object[colsNum];
for(int i=0;i<arr.length;i++)
arr[i]=rs.getObject(i+1);
list.add(arr);
}
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
public static ResultSet executeQuery(String sql){
ResultSet rs=null;
try {
conn = DriverManager.getConnection(url, user, pwd);
Statement cmd = conn.createStatement();
rs=cmd.executeQuery(sql);
} catch (Exception ex) {
ex.printStackTrace();
}
return rs;
}
public static int executeUpdateByParams(String sql,Object... params){
//可变参数
int r=0;
try {
Connection conn = DriverManager.getConnection(url, user, pwd);
PreparedStatement cmd=conn.prepareStatement(sql);