一、前言
本次操作建立在idea中java环境已配置的基础上
二、操作步骤
1.建立Web项目后,添加驱动包 mysql-connector-java-5.0.8-bin.jar
(1)下载mysql-connector-java-5.0.8-bin.jar包
(2)在WEB-INF下新建名字为lib的Directory文件夹
(3)将下载的mysql-connector-java-5.0.8-bin.jar包粘贴进lib文件夹(如下图所示)
(4)导包 File---------Project Structure-------Libraries
打开对应设置
点击+号选择java
找到刚刚复制到bin目录下的mysql-connector-java-5.0.8-bin.jar
然后点击ok,apply,ok。
2.在jsp页面中加载数据库驱动并创建数据库连接,关键代码如下:
<%--
Created by IntelliJ IDEA.
User: 15831851229
Date: 2021/6/3
Time: 17:39
To change this template use File | Settings | File Templates.
--%>
<%@page import="java.sql.PreparedStatement"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.sql.Connection" %>
<%@page import="java.sql.DriverManager" %>
<% request.setCharacterEncoding("UTF-8"); %>
<jsp:useBean id="user" class="bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="user"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<a href='Depart.jsp'>返回首页</a>
<%
request.setCharacterEncoding("utf-8");
String C_title = request.getParameter("Ctitle"); //获取上一个页面表单传name=“Ctitle”过来的值
String E_title = request.getParameter("Etitle");
String C_zhai = request.getParameter("Czhai");
String E_zhai = request.getParameter("Ezhai");
String C_key = request.getParameter("Ckey");
String E_key = request.getParameter("Ekey");
String Page = request.getParameter("page");
Class.forName("com.mysql.jdbc.Driver"); //加载数据库驱动
String url ="jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8"; //数据库连接字符串
String username="root";// 数据库用户名
String password="123456"; //数据库密码
Connection con = DriverManager.getConnection(url, username, password); //创建Connection连接 之后可以通过if(con!=null)判断是否连接
String sql="insert into passage(C_title,E_title,C_zhai,E_zhai,C_key,E_key,Page) values(?,?,?,?,?,?,?)";
PreparedStatement stmt = con.prepareStatement(sql); //获取PrepareStatement接口
stmt.setString(1, C_title); //对sql语句中的第一个参数赋值
stmt.setString(2, E_title);
stmt.setString(3, C_zhai);
stmt.setString(4, E_zhai);
stmt.setString(5, C_key);
stmt.setString(6, E_key);
stmt.setString(7, Page);
int i = stmt.executeUpdate(); //执行更新操作,返回所影响的行数
// if (i == 1) {
// out.println("<h2>添加成功!</h2><br/>");
// out.println("<a href='index.jsp'>返回首页</a>");
// } else {
// out.println("<h2>添加失败!</h2><br/>");
// out.println("<a href='add.jsp'>重新添加</a>");
// }
stmt.close(); //关闭PrepareStatement接口,释放资源
con.close()