jar包位置: D:\机房存放版本(javaDeveloperLibarys)
一定要Tomcat8.0 否则无法用注解
Mysql 账户:root 密码:空
jsp 设置编码格式步骤:
1 在Eclipse菜单栏选中【window】-【Perferences】
2.
项目结构
DBUtil类
package com.zyg.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
//链接数据库
public class DBUtil {
private static String user = "root";
private static String password = "";
private static String url = "jdbc:mysql://localhost:3306/exam?characterEncoding=utf-8";
private static Connection connection;
private static PreparedStatement statement;
private static ResultSet rs;
static {
try {
/**
* 通过路劲动态加载Driver驱动
*/
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 定义getConnection返回数据库链接
public static Connection getConnection() {
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
// 关闭链接
public static void closeAll() throws SQLException {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
/**
* 封装基本的sql操作,查询以及其他操作 此处需要返回值ResultSet ,同时需要将sql作为参数,以及sql操作会传递参数需考虑
*
* @param sql
* @throws SQLException
*/
public static ResultSet select(String sql, Object[] obj) {
connection = getConnection();
try {
statement = connection.prepareStatement(sql);
// 将传递过来的参数进行遍历,全部的放到prepareStatement对象中进行预处理
if (null != obj) {
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
statement.setObject(i + 1, obj[i]);
}
}
// 参数预处理完毕后执行
rs = statement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
/**
* 更新、添加、删除需要执行后的返回值判断是否执行成功
*
* @throws SQLException
*/
public static int update(String sql, Object[] obj) {
connection = getConnection();
try {
statement = connection.prepareStatement(sql);
if (null != obj) {
for (int i = 0; i < obj.length; i++) {
statement.setObject(i + 1, obj[i]);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int i = 0;
try {
i = statement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return i;
}
}