天天看點

批處理檔案 執行java_利用批處理檔案運作java程式

當我們要運作java程式時,可以寫一個批處理檔案(.bat),以便輕按兩下即可運作java程式!

在次測試過程中需要注意的幾個問題:

1、當需要java程式需要引進第三方包時,需要在設定classpath環境時把第三方包路徑給加進去;

2、當運作java程式需要向main()方法傳入參數時,需要在java xxx 後面加上參數值

.bat 檔案代碼:

@echo 測試資料庫連接配接工具set /p ip=請輸入資料庫伺服器IP位址:set /p dataName=請輸入資料庫名:set /p userName=請輸入資料庫登入使用者名:set /p userPwd=請輸入資料庫登入密 碼:

@echo 正在連接配接資料庫,請稍後......//設定classpath,把第三方包路徑引進去

set classpath=.;sqljdbc4.jar//運作java程式時向main函數傳參

java -Xmx512m Test%ip% %dataName% %userName% %userPwd%@pause

.java 程式代碼:

import java.sql.*;public classTest {public static voidmain(String[] srg) {

String driverName= "com.microsoft.sqlserver.jdbc.SQLServerDriver";//加載JDBC驅動

Connection dbConn;try{

Class.forName(driverName);

String dbURL= "jdbc:sqlserver://" + srg[0] +":1433; DatabaseName=" + srg[1];

dbConn= DriverManager.getConnection(dbURL, srg[2], srg[3]);if(!dbConn.isClosed()){

System.out.println("Connection Successful!");//如果連接配接成功//控制台輸出Connection//Successful!

}

}catch(Exception e) {

e.printStackTrace();

}

}

}

測試運作效果:

e:\gngyf18\桌面\測試資料庫連接配接>set /p ip=請輸入資料庫伺服器IP位址:

請輸入資料庫伺服器IP位址:localhost

e:\gngyf18\桌面\測試資料庫連接配接>set /p dataName=請輸入資料庫名:

請輸入資料庫名:sql server

e:\gngyf18\桌面\測試資料庫連接配接>set /p userName=請輸入資料庫登入使用者名:

請輸入資料庫登入使用者名:sa

e:\gngyf18\桌面\測試資料庫連接配接>set /p userPwd=請輸入資料庫登入密 碼:

請輸入資料庫登入密 碼:123

正在連接配接資料庫,請稍後......