作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试查看数据库中的所有数据或向数据库中插入数据。两种方法都给出相同的响应。我的 pojo 类:
public class Title {
private Integer id;
private String name;
private String code;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
我的添加和显示方法的服务类:
public abstract class TitleService {
public static void addTitle(Title title) throws Exception {
Connection c = Global.createConnection();
//Title title=new Title();
PreparedStatement ps = c.prepareStatement(
"insert into Title (id, name, code) values (?, ?, ?)");
ps.setInt(1, title.getId());
ps.setString(2, title.getName());
ps.setString(3, title.getCode());
ps.executeUpdate();
c.commit();
ps.close();
c.close();
}
public static List<Title> allTitles() throws SQLException {
Connection c = Global.createConnection();
Statement st = c.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Title");
List <Title> titles = new ArrayList<>();
Title title;
while (rs.next()) {
title = new Title();
title.setId(rs.getInt(1));
title.setName(rs.getString(2));
title.setCode(rs.getString(3));
titles.add(title);
}
st.close();
c.close();
return titles;
}
}
测试类:
public class ServiceTest {
public static void main(String[] arga) throws SQLException, Exception {
Title t = new Title();
t.setId(1);
t.setCode("Prof");
t.setName("Profesor");
TitleService.addTitle(t);
//TitleService.allTitles();
}
}
当我运行它给出的测试类时,
Exception in thread "main" java.lang.NullPointerException
at service.TitleService.addTitle(TitleService.java:22)
at test.ServiceTest.main(ServiceTest.java:26)
Java Result: 1
TitleService.java:22 ---> PreparedStatement ps = c.prepareStatement(
"insert into Title (id, name, code) values (?, ?, ?)");
ServiceTest.java:26)---> TitleService.addTitle(t);
this exception.
不知道是什么问题
我的全局类敌人数据库连接:
公共(public)抽象类全局{
public static Connection createConnection() {
Connection conn;
System.out.println("Checking if Driver is registered with DriverManager.");
try{
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e){
System.out.println("Couldn't find the driver!");
System.out.println("exit.");
System.exit(1);
}
System.out.println("make a connection.");
try{
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/uni_db", "postgres", "postgres");
System.out.println("Success.");
} catch(SQLException e){
System.out.println("Couldn't connect: exit.");
System.exit(1);}
return null;
}
最佳答案
您正在从 createConnection()
方法返回 null
值您应该返回 Connection
对象。
return conn;
关于java - 数据库项目中线程 "main"java.lang.NullPointerException 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20072682/
我是一名优秀的程序员,十分优秀!