Servlet连接MySQL数据库步骤

MySQL驱动下载:

首先得下载对应数据库的连接驱动包
我用的MySQL数据库所用的驱动是mysql-connector-java-8.0.18.jar
MySQL驱动下载官网: MySQL驱动下载
然后选择下载:
在这里插入图片描述
然后选择一个下载即可.(windows选择第二个)
在这里插入图片描述

Java操作数据库基本流程

1.加载驱动程序

Class.forName("com.mysql.cj.jdbc.Driver");

2.建立连接对象

String dburl = "jdbc:mysql://127.0.0.1:3306/数据库名?useSSL=false&serverTimezone=UTC"
Connection conn = DriverManager.getConnection(dburl,"用户名","密码");

3.创建语句对象

几种对象的创建方式不同:

Statement对象->conn.createStatement()
PreparedStatement对象->conn.prepareStatement()

比如创建Statement对象Statement stmt = conn.createStatement();

4.执行SQL语句并处理结果

ResultSet result = stmt.executeQuery(sql);

while(result.next()){
	out.println(result.getString(1)+"\t");
}

5.关闭建立的对象

dbconn.close();

示例:

使用PreparedStatement对象来进行SQL语句操作

数据库表结构

在这里插入图片描述

javaBean结构:

package com.demol;
import java.io.Serializable;

public class Product implements Serializable {
    private int id;
    private String pname;
    private String brand;
    private float price;
    private int stock;
    public Product(){}

    public Product(int id, String pname, String brand, float price, int stock) {
        this.id = id;
        this.pname = pname;
        this.brand = brand;
        this.price = price;
        this.stock = stock;
    }
}

逻辑处理的Servlet

package com.demol;

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 java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

@WebServlet(name = "ProductQueryServlet",urlPatterns={"/query-product"})
public class ProductQueryServlet extends HttpServlet {
    Connection dbconn = null;
    public void init() {
        String dburl  = "jdbc:mysql://127.0.0.1:3306/new_schema?useSSL=false&serverTimezone=UTC";
        String username ="用户名";
        String password = "密码";
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            dbconn = DriverManager.getConnection(dburl,username,password);
            System.out.println("数据库连接成功");
        }catch (ClassNotFoundException e1){
            System.out.println(e1+"驱动程序找不到");
        }catch(SQLException e2){
            System.out.println(e2);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //返回所有商品
        ArrayList<Product> productList = null;
        productList = new ArrayList<Product>();
        try{
            String sql = "select * from products";
            PreparedStatement pstmt = dbconn.prepareStatement(sql);
            ResultSet result = pstmt.executeQuery();
            while(result.next()){
                Product product = new Product();
                product.setId(result.getInt("id"));
                product.setPname(result.getString("pname"));
                product.setBrand(result.getString("brand"));
                product.setPrice(result.getFloat("price"));
                product.setStock(result.getInt("stock"));
                productList.add(product);
            }
            if(!productList.isEmpty()){
                request.getSession().setAttribute("productList",productList);
                response.sendRedirect("/displayAllProduct.jsp");
            }else{
                response.sendRedirect("error.jsp");
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String productid = request.getParameter("productid");
            try{
                String sql = "select * from products where id= ?";
                PreparedStatement pstmt = dbconn.prepareStatement(sql);
                pstmt.setString(1,productid);
                ResultSet result = pstmt.executeQuery();
                if(result.next()){
                    Product product = new Product();
                    product.setId(result.getInt("id"));
                    product.setPname(result.getString("pname"));
                    product.setBrand(result.getString("brand"));
                    product.setPrice(result.getFloat("price"));
                    product.setStock(result.getInt("stock"));
                    request.getSession().setAttribute("product",product);
                    response.sendRedirect("displayProduct.jsp");
                }else{
                    response.sendRedirect("error.jsp");
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
    }
    public void destroy(){
        try{
            dbconn.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

  • 18
    点赞
  • 129
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
步骤如下: 1. 下载安装MySQL数据库,并新建一个数据库; 2. 在IDEA中打开一个JavaWeb项目,新增一个Libraries库中添加MySQL的驱动jar包; 3. 在项目的web目录下创建一个数据库连接的配置文件(比如db.properties),并将连接信息配置好,如下所示: driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/数据库名 username=数据库用户名 password=数据库密码 4. 在servlet代码中,通过读取配置文件来获取数据库连接及操作: ``` public class MyServlet extends HttpServlet { private static final String DRIVER; private static final String URL; private static final String USERNAME; private static final String PASSWORD; static { Properties properties = new Properties(); InputStream inputStream = MyServlet.class.getResourceAsStream("/db.properties"); try { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } DRIVER = properties.getProperty("driver"); URL = properties.getProperty("url"); USERNAME = properties.getProperty("username"); PASSWORD = properties.getProperty("password"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); Connection connection = null; try { // 加载驱动 Class.forName(DRIVER); // 获取连接 connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); // 执行SQL语句 String sql = "select * from photo"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { // 从结果集中获取数据 String photoName = resultSet.getString("photo_name"); String photoUrl = resultSet.getString("photo_url"); // 输出数据 out.print("照片名称:" + photoName + ",照片地址:" + photoUrl + "<br/>"); } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } ``` 5. 在浏览器中输入访问地址:http://localhost:8080/MyServlet,即可查询到数据库中的照片信息了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值