简体   繁体   English

无法连接到数据库 java jsp,servlet

[英]Can't connect to database java jsp, servlet

I have to connect to database (MySQL workbench) with netbeans, I have file DBContext to dbcontext file to make the connection我必须使用 netbeans 连接到数据库(MySQL 工作台),我有文件 DBContext 到 dbcontext 文件来建立连接

DBcontext connect successfully DBcontext 连接成功

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DBContext {

    //USE BELOW METHOD FOR YOUR DATABASE CONNECTION FOR BOTH SINGLE AND MULTILPE SQL SERVER INSTANCE(s)
    //DO NOT EDIT THE BELOW METHOD, YOU MUST USE ONLY THIS ONE FOR YOUR DATABASE CONNECTION*/
    public Connection connection;

    public Connection getConnection() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        String url = "jdbc:mysql://" + serverName + "/" + dbName;
        return DriverManager.getConnection(url, user, password);
    }

    //Insert your other code right after this comment
    //Change/update information of your database connection, DO NOT change name of instance variables in this class
    private final String serverName = "localhost";
    private final String dbName = "db_ite1";
    private final String user = "root";
    private final String password = "buiduclong"; // password here

    public static void main(String[] args) {
        // Test connection
        try {
            Connection test = new DBContext().getConnection();
            PreparedStatement testStatement = test.prepareStatement("SELECT * FROM db_ite1.blog;");
            System.out.println("suces");
        } catch (Exception e) {
            System.out.println("Fail");
        }
    }
}

And I have a function get data from database, it works and returns data 我有一个 function 从数据库中获取数据,它可以工作并返回数据
        DAO dao = new DAO();
        List<User> list = dao.getAllUser();
        request.setAttribute("UserList", list);
        request.getRequestDispatcher("userlist.jsp").forward(request, response);

then I call this function in servlet but it returns no data, my List has size = 0 even though I check my getAllUser() function returns data Code in servlet 然后我在 servlet 中调用此 function 但它不返回任何数据,我的列表大小 = 0 即使我检查了我的 getAllUser() function 在 servlet 中返回数据代码
 DAO dao = new DAO(); List<User> list = dao.getAllUser(); request.setAttribute("UserList", list); request.getRequestDispatcher("userlist.jsp").forward(request, response);

i'm fixed it, i'm add this string to url "?useSSL=false" at DBContext and it's work我已修复它,我将此字符串添加到 DBContext 的 url "?useSSL=false" 并且它的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM