我正在尝试用Java实现单例数据库连接。我认为我基本上是正确的,但是当我尝试在其他类中使用它时,我一直在获取java.lang.NullPointerExceptions。
我遇到的错误是在我的ProduitDaoImpl类中,在我进行连接的PreparedStatement行上。prepareStatement(query);我认为连接是作为null传递的,但我不知道为什么或如何解决它。
这是我的ProduitDaoImpl
public class ProduitDaoImpl implements IProduitDao {
public List<Produit> produitsParMC(String mc) {
List<Produit> produits=new ArrayList<Produit>();
Connection connection=SingletonConnection.getConnection();
try {
PreparedStatement ps=connection.prepareStatement("SELECT * FROM PRODUITS WHERE DESIGNATION LIKE ?");
ps.setString(1, mc);
ResultSet rs=ps.executeQuery();
while(rs.next()){
Produit p=new Produit();
p.setId(rs.getLong("ID"));
p.setDesignation(rs.getString("DESIGNATION"));
p.setPrix(rs.getDouble("Prix"));
p.setQuantite(rs.getInt("QUANTITE"));
produits.add(p);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return produits;
}
}
这是我的单身人士
public class SingletonConnection {
private static Connection connection;
//le block static charge la classe en mémoire lors de son appel
static{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try {
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/db-natal","root","");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
return connection;
}
}
您的Singleton实现不正确。 (如果您不熟悉此功能(我想是您是,那么请参考https://medium.com/@kevalpatel2106/how-to-make-the-perfect-singleton-de6b951dfdb0或任何其他在线可用的指南。)
Zlxo,创建一个单例连接对象以供所有用户在应用程序之间共享,对于各种因素而言,这不是一个好方法。
无论如何,请在下面检查您可以在代码中检查的可能内容;
Singleton类是否确实正确创建了连接对象?SingletonConnection类中的凭据是否正确?
添加System.out.println(connection);
之前的PreparedStatement ps=connection.prepareStatement(<your query>);
在ProduitDaoImpl类中。
它打印空值还是一些字符串?
如果为null,则可能重新检查用于获取单例类中的连接对象的连接字符串。
如果发现有帮助,请对此答案投票! :)