[英]sqlite function that delete row (java)
我是SQL初學者。 我必須在sqlite中編寫一個獲取db文件的函數。 db文件包含很多表。 該功能需要在年齡列中進行搜索。 當年齡小於20歲時,我需要刪除該行。
例如:第一個表:
age - name
40 - Din
12 - Tayler
60 - George
第二張表:
id - name - country - age
1 - obama - usa - 45
2 - ari - austarlia- 7
運行函數后:
第一張桌子:
age - name
40 - Din
60 - George
第二張表:
id - name - country - age
1 - obama - usa - 45
我啟動了代碼(在附帶的圖片中 )
可以將這個問題分解為以下步驟:1.查找所有表名。 2.循環瀏覽每個表並刪除年齡小於20的行。
我添加了以下代碼,但是您可能需要根據需要自定義它。
public class UpdateDB {
public static void main(String[] args) {
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:/Users/Andrei/test.db");
String sql = "SELECT * FROM sqlite_master WHERE type='table'";
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
List<String> tableNames = new ArrayList<>();
// loop through the result set
while (rs.next()) {
tableNames.add(rs.getString(3));
}
System.out.println("BEFORE UPDATE");
System.out.println("---------------------------");
for (String table: tableNames) {
String sqlUpdate = "SELECT * FROM " + table + " ";
ResultSet rs2 = stmt.executeQuery(sqlUpdate);
while(rs2.next()) {
System.out.println(rs2.getInt("ID") + " " + rs2.getString("AGE"));
}
}
// This is the statement which deletes the rows
for (String table: tableNames) {
String sqlUpdate = "DELETE FROM " + table + " WHERE AGE < 20";
stmt.executeUpdate(sqlUpdate);
}
System.out.println();
System.out.println("AFTER UPDATE");
System.out.println("---------------------------");
for (String table: tableNames) {
String sqlUpdate = "SELECT * FROM " + table + " ";
ResultSet rs2 = stmt.executeQuery(sqlUpdate);
while(rs2.next()) {
System.out.println(rs2.getInt("ID") + " " + rs2.getString("AGE"));
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.