GOT IT WORKING。感謝大家的幫助將值插入到數據庫中
我是新來編程,我試圖檢查,如果我的數據庫是空的。如果它是空的,它會插入一條記錄。如果不是,它應該運行正常。我還檢查文件路徑是否存在於我的映像中。
每次運行該程序時,都會添加「John」(只有在數據庫爲空時才能添加John)。
我的代碼:
public class Database {
private ArrayList<Person> people;
public Database(){
people = new ArrayList<Person>();
}
public void run(){
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager
.getConnection("jdbc:sqlite:C:\\Users\\James\\Documents\\GoogleApp\\Peopleinfo.sqlite");
statement = connection.createStatement();
if(people.isEmpty()){
File f = new File ("C:\\Users\\James\\Documents\\GoogleApp\\images\\upload.png");
if (f.exists()){
String sql = "INSERT INTO PeoplesInfo (Name,bio,Image) " +
"VALUES ('John','California','C:\\Users\\James\\Documents\\GoogleApp\\images\\upload.png');";
statement.executeUpdate(sql);
System.out.println("Image exists");
}
else {
System.out.println("Image doesn't exist");}
}
else if (!people.isEmpty()) {
String sql = "INSERT INTO PeoplesInfo (Name,bio,Image) " +
"VALUES ('Stan','California','C:\\Users\\James\\Documents\\GoogleApp\\images\\upload.png');";
statement.executeUpdate(sql);
System.out.println("Record added");
}
resultSet = statement
.executeQuery("SELECT name, bio, image FROM PeoplesInfo");
while (resultSet.next()) {
Person p = new Person(resultSet.getString("name"),resultSet.getString("bio"),resultSet.getString("image"));
people.add(p);
System.out.println(p.toString());
System.out.println("Retrieved element is = " + p.getName());
}
resultSet = statement
.executeQuery("SELECT name, bio, image FROM PeoplesInfo");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public ArrayList<Person> getPeople(){
return people;
}
}
提前非常感謝。
看起來你正在檢查你的ArrayList是否爲空而不是數據庫。 'people.isEmtpy()'可能總是如此,因爲您沒有向ArrayList添加任何內容。 –
用數據交換填充人的位,以及插入位,具體取決於人員是否爲空。 –
此外,由於各種原因,保留一個長壽命的複製對象圖,內存中的數據庫將給你帶來很多麻煩。 –