Java:无法建立与数据库服务器的连接

时间:2018-09-22 13:12:48

标签: java mysql

我正在做一个简单的Java应用程序,它使用jdbc连接到mysql

    public class DataBaseHelper {
    private ResultSet data = null;
    private Connection connection;
    private Statement query;
    ArrayList<User> users = new ArrayList<>();
    public DataBaseHelper() {
        try {
            //String dbName = "bot";
            String url = "jdbc:mysql://localhost:3306/bot?autoReconnect=true&useSSL=false";
            String userName = "bot_manager";
            String password = "password";
            connection = DriverManager.getConnection(url, userName, password);
            query = connection.createStatement();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    public ArrayList getData() {


        try {
            data = query.executeQuery("select * from users");
            while (data.next()) {
                users.add(new User(data.getLong("user_id")));
            }

        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }

        return users;
    }
}

我使用Ubuntu 16.04,并安装了mysql-server和mysql-client。当我尝试通过“ mysql -u bot_manager -p”手动连接到mysql时,我可以连接到数据库。但是,当我启动jar时,出现以下错误:

Could not create connection to database server. Attempted reconnect 3 times. Giving up.
Exception in thread "main" java.lang.NullPointerException
    at com.package.DataBaseHelper.getData(DataBaseHelper.java:30)
    at com.package.Bot.main(Bot.java:45)

第30行是data = query.executeQuery("select * from users"); 在主体中,我创建一个DataBaseHelper对象(为什么它不会在那里崩溃?),然后调用getData,最后是错误。这是什么问题?

0 个答案:

没有答案