建立model(实体类,也就是把数据库表的字段映射为你的对象的各个属性)
然后是util包
使用Oracle肯定要导入包
使用java web要在web inf 文件的lib目录下添加jdbc包
然后编写DBLink- 这个是用来连接数据库的工具类
我们写一个静态方法来连接数据库
public class DBLink {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println(getCon());
}
//连接数据库
public static Connection getCon() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"system","zhang");
//system是你Oracle的账号 zhang是我自己的口令
return connection;
}
//数据的插入 成功返回1 失败返回0
public static int insertEmp(String name,Double salary,int age) throws SQLException, ClassNotFoundException {
Connection connection = getCon();
String insertSql = "insert into t_emp values (seq_t_emp.nextval,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertSql);
preparedStatement.setString(1,name);
preparedStatement.setDouble(2,salary);
preparedStatement.setInt(3,age);
int i = preparedStatement.executeUpdate();
return i;
}
}
可以运行一下main方法测试数据库连接是否成功
这样就表示成功连接
写一个注册页面
写一个添加类(servelet)
public class AddEmp extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//设置编码统一 数据库一般都是 utf-8 我们只需要设置 网页端 和 本地
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("name");
Double salary = Double.parseDouble(request.getParameter("salary"));
int age = Integer.parseInt(request.getParameter("age"));
try {
if ( DBLink.insertEmp(name,salary,age)>0){
response.sendRedirect("success.jsp");
}
} catch (SQLException | ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
}
然后在web inf中配置severlet
<servlet>
<servlet-name>AddEmp</servlet-name>
<servlet-class>action.AddEmp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddEmp</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
然后就好了
然后是如何列出数据库所有数据
public static ArrayList<Emp> getAll() throws SQLException, ClassNotFoundException {
//数组list 泛型Emp 用来存放Emp
ArrayList<Emp> empArrayList = new ArrayList<>();
String querySql = "select * from t_emp";
Connection connection = DBLink.getCon();
PreparedStatement preparedStatement = connection.prepareStatement(querySql);
//把查询结果返回给resultSet
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
Emp emp = new Emp();
emp.setName(resultSet.getString("name"));
emp.setSalary(resultSet.getDouble("salary"));
emp.setAge(resultSet.getInt("age"));
empArrayList.add(emp);
}
return empArrayList;
}
```
关于登录只需要用数据库查询
select * from t_emp where name=? and password=?