Java无法连接到localhost

时间:2017-12-02 11:07:21

标签: java database jdbc mariadb

我正在尝试连接到localhost上的MariaDB数据库(使用xampp)。我第一次连接时,建立了连接,我设法创建一个包含两个字段“username”“password”的表。此后,当我尝试执行任何其他操作时,Connection将变为null,并且无法插入或执行任何查询。

import java.sql.*;

class MyDatabase {
    private Connection conn;
    private PreparedStatement psAddPerson;


    MyDatabase(String host, String user, String password) throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mariadb:" + host,
                user, password);
        psAddPerson = null;
    }

    public void addPerson(String username, String password) {
        try{
            if( psAddPerson == null ){
                String sqlAddPerson = "insert into users (usern, pass) values (?,?)";
                psAddPerson = conn.prepareStatement(sqlAddPerson);
            }
            psAddPerson.setString(1, username);
            psAddPerson.setString(2, password);
            psAddPerson.executeUpdate();
        } catch (SQLException e) {
            System.err.println("Couldn't create add person");
            e.printStackTrace();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        String host = "//localhost:3306/test";
        String user = "root";
        String pass = "";
        MyDatabase newDb = null;
        try {
            newDb = new MyDatabase(host, user, pass);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String username = "admin";
        String password = "password";
        if (newDb != null) {
            newDb.addPerson(username, password);
        }
    }
}

尝试执行以下代码时,此代码会产生NullPointerException:

psAddPerson = conn.prepareStatement(sqlAddPerson);

我希望能够对我的localhost数据库执行查询。

来自phpMyAdmin服务器类型的图片: Picture of server type

由于

3 个答案:

答案 0 :(得分:2)

改变这个:

Connection conn = DriverManager.getConnection("jdbc:mariadb:" + host, user, password);

由此:

conn = DriverManager.getConnection("jdbc:mariadb:" + host, user, password);

这样您就可以在构造函数中实例化实例变量而不是局部变量。

希望这有帮助!

答案 1 :(得分:1)

修复很容易改变:

Connection conn = DriverManager.getConnection("jdbc:mariadb:" + host,
            user, password);

为:

conn = DriverManager.getConnection("jdbc:mariadb:" + host,
            user, password);

答案 2 :(得分:0)

稍微调整一下并改变一下:

Connection conn = DriverManager.getConnection("jdbc:mariadb:" + host, user, password);

到此:

conn = DriverManager.getConnection("jdbc:mariadb:" + host, user, password);