Reputation: 19
I want to make Connection to MySql serwer with Java(without installing additional extension), and i'm getting "java.lang.NullPointerException" error. Here are my codes Main:
package sqlconnect;
public class SQLcONNECT {
public static void main(String[] args) {
DBConnect connect = new DBConnect();
connect.getData();
}
}
and DBConnect:
package sqlconnect;
//https://dev.mysql.com/downloads/connector/j/
import java.sql.*;
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
String Query = "SELECT * FROM uczniowie;" ;
public void DBConnect()
{
try{
Class.forName("com.mysql.jdbc.Driver") ;
con = DriverManager.getConnection("jdbc:mysql://serwer:port/BaseName","login","passwd");
}catch(Exception ex){
System.err.println(ex);
}
}
public void getData()
{
try
{
st = con.createStatement();
rs = st.executeQuery(Query);
System.out.println("Rows from Table:");
while(rs.next())
{
String Uczen = rs.getString("Uczen");
String CzyZda = rs.getString("CzyZda");
String Ocena = rs.getString("Ocena");
System.out.println("Uczen: " + Uczen +" "+ "CzyZda: "+ CzyZda+"Ocena: "+Ocena);
}
}
catch(Exception ex)
{
System.err.println(ex);
}
} }
What can be problem, and what can i made to solve that?
Upvotes: 0
Views: 807
Reputation: 140309
public void DBConnect()
This isn't a constructor: it's a regular method. This is never invoked because you don't invoke it explicitly.
Remove the void
.
Additionally, don't catch the Exception
. Just add throws Exception
(or, hopefully, a more specific exception) to the method signature. Otherwise you can end up with an invalid, unusable instance of the class.
public DBConnect() throws Exception
{
Class.forName("com.mysql.jdbc.Driver") ;
con = DriverManager.getConnection("jdbc:mysql://serwer:port/BaseName","login","passwd");
}
Upvotes: 3