简体   繁体   English

Java连接到MySql数据库,NullPointerException

[英]Java connection to MySql database, NullPointerException

I want to make Connection to MySql serwer with Java(without installing additional extension), and i'm getting "java.lang.NullPointerException" error. 我想用Java(不安装其他扩展名)连接到MySql服务器,并且出现“ java.lang.NullPointerException”错误。 Here are my codes Main: 这是我的代码Main:

package sqlconnect;
public class SQLcONNECT {
public static void main(String[] args) {
    DBConnect connect = new DBConnect();
    connect.getData();
    }    
}

and DBConnect: 和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? 可能是什么问题,我该怎么解决?

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 . 去除void


Additionally, don't catch the Exception . 此外,不要捕获Exception Just add throws Exception (or, hopefully, a more specific exception) to the method signature. 只需向方法签名添加throws Exception (或者希望是更具体的异常)。 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"); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM