2012-09-27 183 views
8

我需要獲取MySQL的安裝路徑才能執行導出並通過java代碼導入數據庫。目前正在使用eclipse。我需要在一個字符串變量「mySqlPath」中獲取安裝路徑。獲取MySQL安裝路徑

File fMysqlPath = new File("C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\"); 
String executeCmd = "mysqldump -u " + Constants.DB_USER + " -p" + 
        Constants.DB_PASSWORD + " " + Constants.DB_NAME + " -r " + 
        FilePath + "\\" + FileName; 
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd, null, fMysqlPath); 

這就是我所做的。這有一個依賴性問題。

我該如何解決這個問題?

+0

你到底面臨什麼問題? – gprathour

+0

@GPS當我在另一個系統中運行程序時,mysql路徑出錯。 – Gapchoos

回答

10

你有沒有嘗試過這樣的:

import java.sql.*; 
import javax.sql.*; 

public class MysqlPathFinderDemo{ 

public static void main(String args[]){ 
String dbtime; 
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname"; 
String dbClass = "com.mysql.jdbc.Driver"; 
String query = "Select * FROM users"; 

try { 

     Class.forName("com.mysql.jdbc.Driver"); 
     Connection con = DriverManager.getConnection (dbUrl); 
     Statement stmt = con.createStatement(); 
     res = Myconnection.st.executeQuery("select @@datadir"); 
     String Mysqlpath = ""; 

     while(res.next()){ 
      Mysqlpath=res.getString(1) ; 
     } 

     Mysqlpath = Mysqlpath.replace("Data", "bin"); 
     System.err.println("Mysql path is :"+a); 
    } catch(Exception ee) { 
    } 
} 
} 
+1

+1,這是一個很好的破解;) – Sujay

+2

可以使用@@ basedir代替嗎? – Gapchoos

+0

@Franklin這會產生一個異常。在這種情況下,我的MySQL路徑是C:\ Documents and Settings \ All Users \ Application Data \ MySQL \ MySQL Server 5.5 \ bin;替換語句將Application Data替換爲Application bin。 – Gapchoos

3

您可以直接查詢和mysql問自己,給你的路徑:

SHOW VARIABLES LIKE 'basedir'; 

或更容易,

SELECT @@basedir; 

應該給你的安裝路徑。雙方應該導致這樣的:

C:\ Program Files文件\的MySQL \ MySQL服務器5.1 \

datadir是等於拿到數據目錄(數據所在)的路徑。