I'm trying to connect to my MariaDB database which is on localhost (using xampp). The first time I connect, the connection is established and I managed to create a table with the two fields "username" "password". Thereafter, when I try to do anything else, the Connection turns null and I cannot insert or execute any queries.
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);
}
}
}
This code produces a NullPointerException when trying to execute following code:
psAddPerson = conn.prepareStatement(sqlAddPerson);
I want to be able to execute queries to my localhost database.
Picture from phpMyAdmin of server type:
Thanks