나는 전문 프로그래머가 아니며 이것은 나의 첫 번째 자바 애플리케이션이지만 데이터베이스 검증도하기로 결정했다. 다행히도 sqlite 데이터베이스에는 데이터베이스의 각 테이블에 대한 sql 문이있는 시스템 테이블이 있습니다.
첫 번째 질문에 관해서
public class Model {
private Map<String, String> tableSql;
Model(){
// declare right database's tables syntax
tableSql = new HashMap<String, String>();
tableSql.put("settings", "CREATE TABLE [settings] ([id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [item] ...)");
tableSql.put("scheta", "CREATE TABLE [scheta] ([id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [sname] ...)");
tableSql.put("nomera", "CREATE TABLE [nomera] ([id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [nvalue] ...)");
tableSql.put("corr", "CREATE TABLE [corr] ( [id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [cname] ...)");
tableSql.put("category", "CREATE TABLE [category] ([id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [cname] ...)");
tableSql.put("price", "CREATE TABLE [price] ([id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [cdate] ...)");
}
public void Connect(String path){
File DBfile = new File (path);
boolean DBexists = DBfile.exists();
Statement stmt = null;
ResultSet rs;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + path);
c.setAutoCommit(true);
stmt = c.createStatement();
if(DBexists){
// check database structure
for (String tableName : tableSql.keySet()) {
rs = stmt.executeQuery("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = '" + tableName + "'");
if(rs.isBeforeFirst()){
rs.next();
// table and field names may be inside square brackets or inside quotes...
String table_schema_there = rs.getString(1).replaceAll("\\s+"," ").replaceAll("[\\[\\]'`]", "\"");
String table_schema_here = tableSql.get(tableName).replaceAll("\\s+"," ").replaceAll("[\\[\\]'`]", "\"");;
if(! table_schema_there.equals(table_schema_here)){
notifyListeners(new ModelResponse(false, "Structure error. Wrong structure of table " + tableName));
System.exit(0);
}
}
else{
notifyListeners(new ModelResponse(false, "Structure error. The table is missing: " + tableName));
System.exit(0);
}
}
}
else{
// empty DB file created during connection so we need to create schema
for (String tableName : tableSql.keySet()) {
stmt.executeUpdate(tableSql.get(tableName));
}
}
}
catch (Exception e) {
notifyListeners(new ModelResponse(false, e.getMessage()));
System.exit(0);
}
}
}
, 내가 SQL 명령의 텍스트 파일 읽기는 그 같은 SQL 명령을 퍼팅보다 다른 표시되지 않습니다 : 그래서 데이터베이스 구조를 확인하는 신속하고 더러운 방법이 'static final String'을 사용합니다. 당신은 어딘가에 SQL을 작성해야합니다. 코드 외부에서 가져온 것은 무엇입니까? – RustyTheBoyRobot
두 번째 질문과 관련하여 처음에 작성한 DB 스키마와 프로그램 전체에서 사용했던 DB 스키마가 서로 다른 유스 케이스는 무엇입니까? – RustyTheBoyRobot
@RustyTheBoyRobot 1- : 저는 하드 코드 된 문자열을 좋아하지 않습니다. 문자열의 내용을 변경해야 할 경우 응용 프로그램을 다시 작성해야하기 때문입니다. 내가 잘못? 2 : DB가 손상되었거나 사용자가 잘못된 DB 파일을 가리킬 수 있습니다. –