zoukankan      html  css  js  c++  java
  • JDBC原生数据库连接

    我们在开发JavaWeb项目时,常会需要连接数据库。我们以MySQL数据库为例,IDE工具为eclipse,讲述数据库连接与基本操作。

    第一步,我们在Web项目的WebContent中建一个简单的前端页面login.html,内容如下:

    <!DOCTYPE html> 
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录页</title>
    </head>
    <body>
        <p>
            请登录
        </p>
        <form action="LoginServlet" method="post">
            <p><input type="text" placeholder="请输入用户名" name="username"> </p>
            <p><input type="password" placeholder="请输入密码" name="userpwd"> </p>
            <p><input type="submit" value="登录"> </p>
        </form>
    </body>
    </html>
    

    接着,我们修改WebContent--->WEB-INF中的web.xml,对里面的配置做如下修改:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
        <welcome-file-list>
            <welcome-file>login.html</welcome-file>
        </welcome-file-list>
        <servlet>
            <servlet-name>LoginServlet</servlet-name>
            <servlet-class>com.itszt.demo.LoginServlet</servlet-class>
        </servlet>
        <servlet-mapping>
          <servlet-name>LoginServlet</servlet-name>
            <url-pattern>/LoginServlet</url-pattern>
        </servlet-mapping>
    </web-app> 
    

    第二步,我们在Web项目的WebContent--->WEB-INF中看有无名称为lib的文件夹,若没有则建立一个名称为lib的文件夹,若有则使用该文件夹,然后将mysql驱动文件拷贝到lib文件夹里,将其添加到引用库。同时,在Java Resources--->src中建立名称为db-config.properties的属性配置文件,该文件内容为:

    db.DRIVER=com.mysql.jdbc.Driver
    db.URL=jdbc:mysql://localhost:3306/itszt2
    db.USERNAME=root
    db.PASSWROD=2017
    

    第三步,我们在Java Resources--->src中分别建立两个文件夹com.itszt.demo和com.itszt.utils,在com.itszt.demo文件夹中创建一个名称为LoginServlet.java的Servlet文件,用以接收与处理前端页面传来的数据;在com.itszt.utils里创建一个名称为Util_1_JDBC.java的工具类文件,用以处理数据库连接。

    Util_1_JDBC.java文件内容如下:

    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    import java.util.ResourceBundle;
    /**
     * 连接数据库,以及释放资源
     */
    public abstract class Util_1_JDBC {
        private static String DB_DRIVER=null;
        private static String DB_URL=null;
        private static String DB_USER=null;
        private static String DB_PASSWORD=null;
        //注册mysql驱动
        static {
        //也可以采用ResourceBundle来解析与读取属性文件里的配置信息;我们在此采用Properties类加载属性文件
    //        ResourceBundle bundle = ResourceBundle.getBundle("db-config");
    //        String DB_DRIVER=bundle.getString("db.DRIVER");
    //      ...
            Properties properties=new Properties();
            InputStream resourceAsStream = Util_1_JDBC.class.getClassLoader().getResourceAsStream("db-config.properties");
            try {
                properties.load(resourceAsStream);
                String DB_DRIVER = properties.getProperty("db.DRIVER");
                String DB_URL = properties.getProperty("db.URL");
                String DB_USER = properties.getProperty("db.USERNAME");
                String DB_PASSWORD = properties.getProperty("db.PASSWROD");
            } catch (IOException e) {
                throw new RuntimeException("读取属性文件失败!");
            }
            try {
                Class.forName(DB_DRIVER);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("注册驱动失败!");
            }
        }
        /**
         * 打开与数据库的连接
         * @return 一个连接对象
         */
        public static Connection openConnection(){
            try {
                return DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return null;
        }
        //释放资源
        public static void release(Connection connection, Statement statement, ResultSet resultSet){
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    我们再来看LoginServlet.java的内容: 

    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.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    @WebServlet(name = "LoginServlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            String username = request.getParameter("username");
            System.out.println("username="+username);
            String userpwd = request.getParameter("userpwd");
            System.out.println("userpwd="+userpwd);
            PreparedStatement statement=null;
            ResultSet resultSet=null;
            //1.不采用数据源连接池,需要频繁建立与数据库的连接与释放资源
    Connection connection = UtilJDBC.openConnection();
            try {
            statement=connection.prepareStatement("SELECT * FROM users where username=? AND  userpwd=?");
            statement.setString(1,username);
            statement.setString(2,userpwd);
            resultSet = statement.executeQuery();
            if(resultSet.next()){//判断查询结果集中有无数据,有则表示存在;也可以用resultSet.hasNext()判断
                System.out.println("登录成功!");
            }else{
                System.out.println("登录失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            Util_1_JDBC.release(connection,statement,resultSet);
        }

          }  

         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        doPost(request, response);
        }
    }

    另外,数据库名称为itszt2,要访问的表users的结构为:

    CREATE TABLE `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(20) NOT NULL,
      `userpwd` varchar(20) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    

    该表中存了一条数据,即(“xiaoming”,123456)。

  • 相关阅读:
    DM数据库disql的使用 Disql disql 达梦数据库Disql
    移动端禁止蒙层下的页面滚动
    移动端如何自动适配px
    使用Vant做移动端对图片预览ImagePreview和List的理解
    uniapp中使用uView组件库
    h5使用vuephotopreview 做全屏预览
    jsonview的实现
    PC端自适应使用rem 移动端适配升级版
    axios解决跨域问题(vuecli3.0)
    vs code 配置git path
  • 原文地址:https://www.cnblogs.com/lizhangyong/p/8117321.html
Copyright © 2011-2022 走看看