本實驗實現簡單的增加功能,實現連接數據庫。
首先需要在eclipse里建立一個Dynamic Web Project項目,截圖如下
(java web 必須創建在這樣的文件夾內)

點擊上述項目后,會出現如下界面,首先輸入項目的名稱,本次項目名稱為deng_lu,輸入名稱后點擊Finish完成。

建立完項目后看一下項目的總覽,一共有6個東西需要添加,添加完這六個東西后,再在navicat里加一個表就可以完成了:

1.首先Bean的代碼如下
package bean;
public class Bean {
private String zhanghao;
private int password;
private String shenfen;
public String getZhanghao() {
return zhanghao;
}
public void setZhanghao(String zhanghao) {
this.zhanghao = zhanghao;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getShenfen() {
return shenfen;
}
public void setShenfen(String shenfen) {
this.shenfen = shenfen;
}
public Bean(String zhanghao,int password,String shenfen) {
this.zhanghao = zhanghao;
this.password = password;
this.shenfen = shenfen;
}
public String toString() {
return "Bean [zhanghao=" + zhanghao + ", password=" + password + ", shenfen=" + shenfen + "]";
}
}
2.Dao類代碼如下
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import bean.Bean;
import db.DBUtil;
public class Dao {//dao層
private DBUtil dbutil=new DBUtil();
public Dao() {
// TODO Auto-generated constructor stub
}
public boolean insert(Bean bean) {//插入數據的方法
boolean f=false;
String sql="insert into denglu(zhanghao,password,shenfen) values('"+bean.getZhanghao()+"','"+bean.getPassword()+"','"+bean.getShenfen()+"')";
Connection conn=DBUtil.getConnection();//數據庫連接,加載驅動
Statement state=null;//?定義state對象
try
{
state=conn.createStatement();//實例化Statement對象,方便對sql語句進行操作
System.out.println(conn);//?
state.executeUpdate(sql);//?
f=true;
//執行數據庫更新操作用於執行INSERT、UPDATE或DELETE語句以及SQLDDL(數據定義語言)語句,
//例如CREATETABLE和DROPTABLE,(創建表和刪除表)
}catch(Exception e)//當try語句中s出現異常時,會執行catch中的語句
{
e.printStackTrace();//捕獲異常的語句
}
finally //finally作為異常處理的一部分,它只能用在try/catch語句中,並且附帶一個語句塊,表示這段語句最終一定會被執行(不管有沒有拋出異常),經常被用在需要釋放資源的情況下。
{
DBUtil.close(conn);
}
return f;
}
}
3.DBUtil類代碼如下:
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
private static String url = "jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
private static String user = "root";
private static String password = "3wcnasdqaz";
private static String jdbcName="com.mysql.cj.jdbc.Driver";
private Connection con=null;
public static Connection getConnection() {
Connection con=null;
try {
Class.forName(jdbcName);
con=DriverManager.getConnection(url, user, password);
//System.out.println("數據庫連接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
//System.out.println("數據庫連接失敗");
e.printStackTrace();
}
try {
con = DriverManager.getConnection(url,user,password);
System.out.println("連接成功");
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
return con;
}
public static void main(String[] args)throws SQLException {
Connection conn = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql ="select * from denglu";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
System.out.println(getConnection());
while(rs.next()){
System.out.println("成功");
}
}
// return con;
public static void close(Connection con) {
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void close(Statement state, Connection conn) {
if(state!=null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement state, Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(state!=null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4.servlet代碼如下:(這個要建立servlet文件)

package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Bean;
import dao.Dao;
/**
* Servlet implementation class servlet
*/
@WebServlet("/servlet")
public class servlet extends HttpServlet {
Dao dao=new Dao();
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public servlet() {
super();
// TODO Auto-generated constructor stub
}
private void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String zhanghao= request.getParameter("zhanghao");
int password= Integer.parseInt(request.getParameter("password"));
String shenfen= request.getParameter("shenfen");
Bean bean=new Bean(zhanghao,password,shenfen);
if(dao.insert(bean)) {//?
request.setAttribute("message", "添加成功");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String method=request.getParameter("method");
if("insert".equals(method)) {
insert(request,response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
5.此為jar包,直接在官網下載然后復制粘貼到 lib 里面即可
mysql-connector-java-8.0.22.jar(此為渣包的名稱)
6.login.jsp代碼如下(這個頁面需要建立jsp頁面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>deng_lu</title>
</head>
<body>
<%
Object message = request.getAttribute("message");
if (message != null && !"".equals(message)) {
%>
<script type="text/javascript">
alert("<%=request.getAttribute("message")%>"); //彈出對話框
</script>
<%
}
%>
<form action="servlet?method=insert" method="post">
賬號:<input type="text" name="zhanghao" id="zhanghao"/><br />
密碼:<input type="password" name="password"id="password" /><br />
身份:<input type="text"name="shenfen"id="shenfen"/><br />
<input type="submit" value="添加"/>
</form>
</body>
</html>
以上是在eclipse里建立的過程,接下來是第7步,也是最后一步,建表

以上是3處需要注意的地方,第一處是庫名,在DBUtil中需要改,第二個是表明在dao中需要改,(建議按照如圖中命名,這樣就不用改代碼中的表名了,如果這樣,所有代碼只需把數據庫的密碼改掉就可以了,了,)
