intellij idea连接MySQL并进行增删改查操作

项目的创建

打开intellij idea创建java工程,在该工程中新建一个文件夹lib,然后复制mysql-connector-java-5.1.36.jar粘贴到lib文件中
在这里插入图片描述
在这里插入图片描述
鼠标右键选择 Add as Library,把jar包导入到工程中
在这里插入图片描述

增删改查操作

数据库已经导入的数据
在这里插入图片描述
1.查询

package com.zrgj.util;

import java.sql.*;

public class Test {
    public static void main(String[] args) {

        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            connection = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&" +
                            "characterEncoding=utf-8&user=" +
                            "root&password=1234");//user为root,密码为1234
            System.out.println("创建连接成功");
            //3.写sql
            String sql = "select * from userinfo";
            //4.得到statement对象
            statement = connection.prepareStatement(sql);
            //5.执行sql得到结果集
            rs = statement.executeQuery();
            //6.处理结果集
            while (rs.next()) {
                System.out.print(rs.getInt(1));
                System.out.print(rs.getString(2));
                System.out.print(rs.getString(3));
            }
            //7.关闭资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

运行结果
在这里插入图片描述
2.插入数据

package com.zrgj.util;

import java.sql.*;

public class insert {
    public static void main(String[] args) {
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            connection = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&" +
                            "characterEncoding=utf-8&user=" +
                            "root&password=1234");
            System.out.println("创建连接成功");
            //3.写sql
            String sql = "insert into userinfo(username,password) values(?,?)";
            //4.得到statement对象
            statement = connection.prepareStatement(sql);
            //5.执行sql得到结果集
            statement =  connection.prepareStatement(sql);
            //6.处理结果集,插入数据
            statement.setString(1, "Rose");
            statement.setString(2, "123");
            statement.executeUpdate();
            System.out.println("插入成功!");
            //7.关闭资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

在这里插入图片描述
在这里插入图片描述
3.修改数据

package com.zrgj.util;

import java.sql.*;

public class update {
    public static void main(String[] args) {
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            connection = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&" +
                            "characterEncoding=utf-8&user=" +
                            "root&password=1234");
            System.out.println("创建连接成功");
            //3.写sql
            String sql = "update userinfo set username=?,password=? where id=?";
            //4.得到statement对象
            statement = connection.prepareStatement(sql);
            //5.执行sql得到结果集
            statement =  connection.prepareStatement(sql);
            //6.处理结果集,插入数据
            statement.setString(1,"abc");
            statement.setString(2,"789");
            statement.setInt(3,1);
            statement.executeUpdate();
            System.out.println("修改成功!");
            //7.关闭资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

在这里插入图片描述
在这里插入图片描述
4.删除数据

package com.zrgj.util;

import java.sql.*;

public class delete {
    public static void main(String[] args) {
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            connection = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&" +
                            "characterEncoding=utf-8&user=" +
                            "root&password=1234");
            System.out.println("创建连接成功");
            //3.写sql
            String sql = "delete from userinfo where id=?";
            //4.得到statement对象
            statement = connection.prepareStatement(sql);
            //5.执行sql得到结果集
            statement.setInt(1,2);
            statement.executeUpdate();
            System.out.println("删除成功!");
            //7.关闭资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

在这里插入图片描述
在这里插入图片描述
对增删改查进行优化
1.创建工具类

package com.zrgj.util;

import java.sql.*;

public class JDBCUtil {
     private static ResultSet rs = null;
     private static PreparedStatement statement = null;
    private static Connection connection = null;
     private JDBCUtil (){}
     static {
         try {
             Class.forName("com.mysql.jdbc.Driver");
         } catch (Exception e) {
             e.printStackTrace();
         }
     }

    public static Connection getConnection(){
         try{
             Class.forName("com.mysql.jdbc.Driver");
             connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&characterEncoding=utf-8&user=root&password=1234");
         }catch (Exception e) {
             e.printStackTrace();
         }
         return connection;
    }

    public static void close(ResultSet rs,Statement stat,Connection conn){
         try {
             if(rs != null) rs.close();
             if(stat != null) stat.close();
             if(conn != null) conn.close();
         }catch (Exception e) {
             e.printStackTrace();
         }finally {
             if (rs != null) {
                 try {
                     rs.close();
                 } catch (SQLException e) {
                     e.printStackTrace();
                 }
             }
             if (statement != null) {
                 try {
                     statement.close();
                 } catch (SQLException e) {
                     e.printStackTrace();
                 }
             }
             if (connection != null) {
                 try {
                     connection.close();
                 } catch (SQLException e) {
                     e.printStackTrace();
                 }
             }
         }
    }
}

2.构造实体类,根据我们数据库表中的属性创建User类

package com.zrgj.bean;

public class userInfo {
    private  int id;
    private  String username;
    private  String password;

    public void setId(int id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}


3.创建持久层,对数据库进行增删改查

package com.zrgj.dao;

import com.whut.bean.userInfo;
import com.whut.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserInfoDao {
    public static void main(String[] args){
        UserInfoDao userdao = new UserInfoDao();
        List<userInfo> list = userdao.findALL();

    }

    public List<userInfo> findALL(){
        PreparedStatement statement = null;
        ResultSet rs = null;
        Connection connection = JDBCUtil.getConnection();
        List<userInfo> list = new ArrayList<>();
        try {
            String sql = "select * from userinfo";
            //4.得到statement对象执行sql
            statement = connection.prepareStatement(sql);
            //5.得到结果集
            rs = statement.executeQuery();

            //6.处理结果集
            while (rs.next()) {
                userInfo uinfo = new userInfo();
                uinfo.setId(rs.getInt(1));
                uinfo.setUsername(rs.getString(2));
                uinfo.setPassword(rs.getString(3));
               // System.out.println(uinfo);
                list.add(uinfo);
            }
            //7.关闭资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(null,statement,connection);
        }
       return list;
    }

    public void add(){
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();

            String sql = "insert into userinfo(username,password) values(?,?)";

            statement =  connection.prepareStatement(sql);

            statement.setString(1, "ccz");
            statement.setString(2, "1234");
            statement.executeUpdate();
            System.out.println("插入成功!");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(null,statement,connection);
        }
    }

    public void update(){
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = JDBCUtil.getConnection();
            //3.写SQL
            String sql = "update userinfo set username=?,password=? where id=?";
            //4.得到statement对象执行sql
            statement = connection.prepareStatement(sql);
            //5.得到结果集
            statement.setString(1,"abc");
            statement.setString(2,"789");
            statement.setInt(3,1);
            statement.executeUpdate();
            System.out.println("修改成功!");
            //6.处理结果集
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(null,statement,connection);
        }
    }

    public void delete(){
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();
            //3.写SQL
            String sql = "delete from userinfo where id=?";
            //4.得到statement对象执行sql
            statement = connection.prepareStatement(sql);
            //5.得到结果集
            statement.setInt(1,2);
            statement.executeUpdate();
            System.out.println("删除成功!");
            //6.处理结果集
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(null,statement,connection);
        }
    }

}


4.对Test进行修改

package com.zrgj;

import com.whut.bean.userInfo;
import com.whut.dao.UserInfoDao;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        UserInfoDao  uinfo = new UserInfoDao();
        List<userInfo> list = uinfo.findALL();
        System.out.println(list);
        uinfo.add();
        List<userInfo> list1 = uinfo.findALL();
        System.out.println(list1);
        uinfo.update();
        List<userInfo> list2 = uinfo.findALL();
        System.out.println(list2);
        uinfo.delete();
        List<userInfo> list3 = uinfo.findALL();
        System.out.println(list3);
    }
}

在这里插入图片描述
在这里插入图片描述
导出完成了代码优化

首先,需要下载并安装MySQL数据库,然后创建一个数据库,并创建一个表格存储数据。 接下来,打开IntelliJ IDEA,创建一个Web应用程序工程。 在工程的src目录下,创建一个Java类,用于连接操作数据库。 ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBHelper { private static String driver = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8"; private static String user = "root"; private static String password = "123456"; public static Connection getConn() { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } public static void closeConn(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static int executeUpdate(String sql) { Connection conn = null; Statement stmt = null; int result = 0; try { conn = getConn(); stmt = conn.createStatement(); result = stmt.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } finally { closeConn(conn); } return result; } public static ResultSet executeQuery(String sql) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = getConn(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; } } ``` 这个类中包含了获取数据连接、关闭数据连接、执行增删改查语句的方法。 接下来,创建一个Servlet的Java类,用于处理Http请求,并调用DBHelper中的方法操作数据库。 ``` import java.io.IOException; import java.io.PrintWriter; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class StudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public StudentServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String action = request.getParameter("action"); if ("add".equals(action)) { String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); String gender = request.getParameter("gender"); String sql = "insert into student(name,age,gender) values('" + name + "'," + age + ",'" + gender + "')"; int result = DBHelper.executeUpdate(sql); if (result > 0) { out.print("<script>alert('添加成功');window.location.href='index.jsp';</script>"); } else { out.print("<script>alert('添加失败');history.go(-1);</script>"); } } else if ("delete".equals(action)) { int id = Integer.parseInt(request.getParameter("id")); String sql = "delete from student where id=" + id; int result = DBHelper.executeUpdate(sql); if (result > 0) { out.print("<script>alert('删除成功');window.location.href='index.jsp';</script>"); } else { out.print("<script>alert('删除失败');history.go(-1);</script>"); } } else if ("update".equals(action)) { int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); String gender = request.getParameter("gender"); String sql = "update student set name='" + name + "',age=" + age + ",gender='" + gender + "' where id=" + id; int result = DBHelper.executeUpdate(sql); if (result > 0) { out.print("<script>alert('修改成功');window.location.href='index.jsp';</script>"); } else { out.print("<script>alert('修改失败');history.go(-1);</script>"); } } else if ("query".equals(action)) { String name = request.getParameter("name"); String sql = "select id,name,age,gender from student where name like '%" + name + "%'"; ResultSet rs = DBHelper.executeQuery(sql); StringBuilder sb = new StringBuilder("<table border='1'>"); sb.append("<tr><th>编号</th><th>姓名</th><th>年龄</th><th>性别</th><th>操作</th></tr>"); try { while (rs.next()) { sb.append("<tr>"); sb.append("<td>" + rs.getInt("id") + "</td>"); sb.append("<td>" + rs.getString("name") + "</td>"); sb.append("<td>" + rs.getInt("age") + "</td>"); sb.append("<td>" + rs.getString("gender") + "</td>"); sb.append("<td><a href='update.jsp?id=" + rs.getInt("id") + "'>修改</a> <a href='StudentServlet?action=delete&id=" + rs.getInt("id") + "'>删除</a></td>"); sb.append("</tr>"); } } catch (Exception e) { e.printStackTrace(); } finally { DBHelper.closeConn(DBHelper.getConn()); } sb.append("</table>"); out.print(sb.toString()); } else { response.sendRedirect("index.jsp"); } out.flush(); out.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 这个Servlet中包含了添加学生记录、删除学生记录、修改学生记录、查询学生记录的方法。 最后,在Web应用程序中创建JSP页面,用于添加、修改、查询和展示学生信息的操作。 以查询学生信息页面query.jsp为例: ``` <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生信息查询</title> </head> <body> <h2>学生信息查询</h2> <form action="StudentServlet" method="get"> 姓名:<input type="text" name="name"> <input type="hidden" name="action" value="query"> <input type="submit" value="查询"> </form> <hr> <h3>查询结果</h3> <%= request.getAttribute("resultStr") %> </body> </html> ``` 在这个页面中,用户可以输入学生姓名,然后点击查询按钮,调用Servlet中的查询学生记录的方法,返回查询结果并显示在页面上。 这样就完成了使用Idea连接MySQL数据库和Servlet进行增删改查操作的示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值