我正在使用 JAVAFX 来创建 SQLite DB 的应用程序。如果 DB 不存在,则必须创建它。代码中显示的函数 getConnection()。 GUI中有表格。输入所有字段的值后,用户将单击“保存”按钮。条目应保存在表中。 实施的方案如下: SAVE按钮事件调用btnsave()->insertrecord()->executequery()->getConnection()
我通过以下方式测试了应用程序:
在 PC1 上安装的 eclipse 中 --> 运行良好。数据库已创建,表条目已成功删除。
创建可运行的 Jar 并复制到其他笔记本电脑 PC2 --.效果与情况 1 一样好。
Inno setup 安装在 PC2 上。所以,使用INNO来制作安装程序。安装在 PC2 上。似乎没有创建数据。如果创建了,不知道会在系统的什么地方创建?如何以编程方式读取数据库路径?
@FXML
private void btnsave(ActionEvent event) throws Exception{
insertrecord();
System.out.println("New Patient Inserted");
}
private void insertrecord() throws Exception
{
try{
String query ="INSERT INTO `newpatient`(patientId,patientName,patientAge,patientGender,patientAddress,patientMobile)"+
"VALUES("+ newpatient_id.getText() +",'" + newpatient_name.getText() + "','"+ newpatient_age.getText() + "',"
+ "'"+ selectedGender + "','"+ newpatient_address.getText() + "',"+ newpatient_mobile.getText() +")";
executeQuery(query);
System.out.println("Saved");
}
catch(Exception e) {
//System.out.println("Execption in Save");
e.printStackTrace();
}
}
private void executeQuery(String query) {
Connection conn= getConnection();
Statement st;
try {
st = conn.createStatement();
st.executeUpdate(query);
}catch(Exception e){
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:patientdata","root","");
System.out.println("data base connection established: "+ conn.toString());
Statement stmt = null;
stmt = conn.createStatement();
String pat = "CREATE TABLE if not exists newpatient " +
"(patientId INTEGER NOT NULL," +
" patientName CHAR(50) NOT NULL, " +
" patientAge INTEGER NOT NULL, " +
"patientGender CHAR(10) NOT NULL,"+
"patientAddress CHAR(100) NOT NULL,"+
"patientMobile BIGINT(10) NOT NULL)";
System.out.println("newpatient Table Created: ");
stmt.executeUpdate(pat);
stmt.close();
stmt = conn.createStatement();
String hist = "CREATE TABLE if not exists history " +
"(id INTEGER NOT NULL," +
" date DATE NOT NULL, " +
" start TIME NOT NULL, " +
"stop TIME NOT NULL)";
System.out.println("history Table Created: ");
stmt.executeUpdate(hist);
stmt.close();
return conn
}
我的脑海中存在一个误解,认为 jdbc:sqlite: 会在安装应用程序的同一文件夹中自动创建数据库文件。但是,安装任何应用程序的文件夹都受到写保护。以下对我有用:
public static Connection getConnection() {
Connection conn = null;
try{
File theDir = new File( "c://spm_database");
if (!theDir.exists()){
theDir.mkdirs();
}
System.out.println(theDir.toString());
String dbpath = theDir.toString()+"/patientdata.db";
System.out.println("Current absolute dbpath is: " + dbpath);
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:"+dbpath);
System.out.println("data base connection established: "+ conn.toString());
// extra code .....
}
catch(Exception e){
}
retrun conn
}