首页 > 技术文章 > Eclipse简单增加连接数据库(tomcat navicat)

wfswf 2020-11-08 00:08 原文

本实验实现简单的增加功能,实现连接数据库。

首先需要在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中需要改,(建议按照如图中命名,这样就不用改代码中的表名了,如果这样,所有代码只需把数据库的密码改掉就可以了,了,)

 

推荐阅读