java基础 通过Servlet&JDBC将student信息入库

需求:

  1. 网页传入信息(name等等)使用Servlet落库。

    1. 根据网页传入的信息,从数据库中查询这一条数据

      1. 新建一个Maven web项目

      导入Servlet的依赖以及mysql驱动

          <!--mysql驱动-->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
          </dependency>
          <!--Servlet-->
          <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
          <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
          </dependency>
      
      2. 编写jdbc
      • 创建db.properties文件,里面包含了数据库的urldriver等信息
      driverClassName=com.mysql.cj.jdbc.Driver
      url=jdbc:mysql://localhost:3306/test?useUnicode=ture&charactorEncoding=utf-8&serverTimezone=UTC
      username=root
      password=123456
      
      • 创建JDBC工具类去拿到connection对象

        通过getConn方法获得connection对象

        通过close方法关闭数据库连接

        public class JDBCUtil {
            private static String driver;
            private static String url;
            private static String username;
            private static String password;
        
            //静态代码块,在程序编译的时候执行
            static {
                try {
                    //创建Properties对象
                    Properties p = new Properties();
                    //获取文件输入流
                    InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
                    //加载输入流
                    p.load(in);
                    //获取数据库连接驱动名字
                    driver = p.getProperty("driverClassName",null);
                    //获取数据库连接地址
                    url = p.getProperty("url",null);
                    //获取数据库连接用户名
                    username = p.getProperty("username",null);
                    //获取数据库连接密码
                    password = p.getProperty("password",null);
                    if(driver != null && url != null
                            && username != null && password != null){
                        //加载驱动
                        Class.forName(driver);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        
            /**
             * 获取连接对象
             * @return Connection连接对象
             */
            public static Connection getConn(){
                Connection conn = null;
                try {
                    conn = DriverManager.getConnection(url,username,password);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return conn;
            }
        
            /**
             * 关闭连接(Connection连接对象必须在最后关闭)
             * @param conn Connection连接对象
             * @param st 编译执行对象
             * @param rs 结果集
             */
            public static void close(Connection conn, Statement st, ResultSet rs){
                try {
                    if(rs != null){
                        rs.close();
                    }
                    if(st != null){
                        st.close();
                    }
                    if(conn != null){
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        
        
      3. 编写Servlet类继承HttpServlet

      重写doGet方法

      使用@WebServlet(name = "StudentInsert", urlPatterns = "/insert")注解设置访问路径

      doGet方法中通过request对象去拿到url中输入的student信息

      拿到的student信息不为空就进行入库操作

      /**
       * @author YonC
       * @date 2021/9/1
       */
      @WebServlet(name = "StudentInsert", urlPatterns = "/insert")
      public class StudentInsert extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
              //设置字符编码
              req.setCharacterEncoding("utf8");
              //从req对象中获取student的信息
              String stuName = req.getParameter("name");
              String stuAge = req.getParameter("age");
              //入库
              if (stuName != null & stuAge != null) {
                  Connection conn = JDBCUtil.getConn();
                  try {
                      String sql = "insert into student (name,age) value (?,?)";
                      //4.得到statement对象
                      PreparedStatement statement = conn.prepareStatement(sql);
                      statement.setString(1, stuName);
                      statement.setString(2, stuAge);
                      //执行sql
                      statement.executeUpdate();
                      JDBCUtil.close(conn, statement, null);
                  } catch (SQLException e) {
                      e.printStackTrace();
                  }
                  System.out.println("进行入库操作完毕....");
                  System.out.println("name=" + stuName);
                  System.out.println("age=" + stuAge);
              }
          }
      
      }
      
      

      配置tomcat后启动。

      访问路径:localhost:8080/insert?name=aaa&age=18添加一个nameaaaage为18的student入库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YonChao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值