This seems like a really simple problem, but I cannot figure out what my problem is. I have a method addTask which adds some info to our database as seen in this code:
public static boolean addTask(String name, String question, int accuracy, int type){
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO tasks (name, question, type, accuracy) ");
sql.append("VALUES(?, ?, ?, ?)");
try {
Connection c = DbAdaptor.connect();
PreparedStatement preparedStatement = c.prepareStatement(sql.toString());
preparedStatement.setString(1, name);
preparedStatement.setString(2, question);
preparedStatement.setInt(3, type);
preparedStatement.setInt(4, accuracy);
preparedStatement.execute();
preparedStatement.close();
c.close();
return true;
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
}
my problem is that preparedStatement.execute() always returns false, indicating the information hasnt been added to the database. I can run psql and this confirms that nothing has been written to the db. The connection definitely connects to the correct database (i put in some other printlns etc. to check this). I am trying to insert into a newly initialised table that looks like this:
CREATE TABLE tasks
(
id SERIAL PRIMARY KEY,
submitter INTEGER REFERENCES accounts (id),
name VARCHAR(100) NOT NULL,
question VARCHAR(100) NOT NULL,
accuracy INTEGER NOT NULL,
type INTEGER REFERENCES types (id),
ex_time TIMESTAMP,
date_created TIMESTAMP
);
code for DbAdaptor.connect():
public static Connection connect(){
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PASSWORD);
try {
return DriverManager.getConnection(URL, properties);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
where USER
and PASSWORD
are static fields in the class
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…