I'm trying to make a custom MySQL class in Java but I'm getting a few exceptions, here's my code:
MySQL.java:
package evo.common;
import java.sql.*;
public class MySQL {
private static String hostname;
private static String username;
private static String password;
private static String database;
public MySQL(String host, String user, String pass, String db)
{
hostname = host;
username = user;
password = pass;
database = db;
}
public static void Error(Exception ex)
{
System.out.println("Fatal Error: "+ex.getMessage());
}
public static void SQLError(SQLException ex)
{
System.out.println("Fatal SQL Error: "+ex.getMessage());
}
private static Connection connect()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch(Exception e){
Error(e);
}
String url = "jdbc:mysql://"+hostname+":3306/"+database;
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch(SQLException ex){
SQLError(ex);
}
return conn;
}
public static ResultSet result(String query)
{
Connection conn = connect();
PreparedStatement pst = null;
ResultSet rs = null;
try
{
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
} catch(SQLException ex){
SQLError(ex);
}
return rs;
}
public static void main(String args[]){}
}
Test.java:
package evo.common;
import java.sql.*;
public class Test {
public static void main(String args[])
{
MySQL mysql = new MySQL("localhost", "root", "******", "souljaz");
ResultSet res = mysql.result("SELECT * FROM users");
}
}
When I run Test I get these error messages in the console:
Fatal Error: com.mysql.jdbc.Driver
Fatal SQL Error: No suitable driver found for jdbc:mysql://localhost:3306/souljaz
Exception in thread "main" java.lang.NullPointerException
at evo.common.MySQL.result(MySQL.java:58)
at evo.common.Test.main(Test.java:8)
I'm quite new to Java so help appreciated. thanks.