问题
I am developing a jframe to store some data in database by using textfields and all. i have following code for database connection. I am using sqlite database.
**Connectdatabase.java**
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author DeepRocks
*/
public class Connectdatabase {
Connection con = null;
public static Connection ConnecrDb(){
try{
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:G:\\Development\\Project\\database\\shreesai.sqlite");
return con;
}
catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"Problem with connection of database");
return null;
}
}
}****
/* ALL IS WORKING FINE WITH THIS BUT I WANT THAT IS IF I EXPORT THIS PROJECT TO JAR AND MY CLIENT WILL RUN JAR FROM DIFFERENT PATH THEN????*/
I've tried using this code
public class Connectdatabase {
Connection con = null;
public static Connection ConnecrDb(){
try{
String dir = System.getProperty("user.dir");
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:"+dir+"shreesai.sqlite");
return con;
}
catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"Problem with connection of database");
return null;
}
}
}
Even i tried this one :
public class Connectdatabase {
Connection con = null;
public static Connection ConnecrDb(){
try{
String dir = System.getProperty("user.dir");
String maindir = dir + File.separator + File.separator ;
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:"+maindir+"shreesai.sqlite");
return con;
}
catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"Problem with connection of database");
return null;
}
}
}
But NOTHING i think there must be problem with that double backslashes cause dir returning : G:\Development\Project\database. and we want G:\\Development\\Project\\database\\
Any help?
回答1:
The ways you're tried are not wrong, but it's right only on your computer, so, the solution is easy, bring the .sqlite
file inside the src
, maybe you want create a package named Database
, it's not required, but it's better.
IF the .sqlite
file was inside the source would be like that:
src/shreesai.sqlite
....=DriverManager.getConnection("jdbc:sqlite:src/shreesai.sqlite");
Don't want the absolute path too, and avoid using backslashes with directories( \\
) because of different windowing platforms, use slash(/
) instead.
来源:https://stackoverflow.com/questions/17978152/how-to-get-realative-path-for-database