十行代碼測試連接數(shù)據(jù)庫

因為項目在多和環(huán)境多個數(shù)據(jù)庫中執(zhí)行,項目代碼連接數(shù)據(jù)庫不成功,所以想做個簡單的工具,單純測試數(shù)據(jù)庫是否能連接成功,以確認數(shù)據(jù)庫網(wǎng)絡(luò)是不是暢通.

編輯TestJdbc.java文件

import java.sql.Connection;
import java.sql.DriverManager;

public class TestJdbc{
    public static void main(String[] args) {
        String driverName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String username = "root";
        String password = "root";

        try {
            Class.forName(driverName);
            Connection conn = DriverManager.getConnection(url,
                    username, password);
            conn.close();
            System.out.println("connect success!\nurl:"+url+"\nusername:"+username
                +"\npassword:"+password+"\ndriverName:"+driverName);
        } catch (Exception e) {
            System.out.println("connect fail!\nurl:"+url+"\nusername:"+username
                +"\npassword:"+password+"\ndriverName:"+driverName);
            e.printStackTrace();
        }
    }
}

或者核心代碼(10行)

import java.sql.Connection;
import java.sql.DriverManager;

public class TestJdbc{
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false",
                "root", "root");
        conn.close();
    }
}

將數(shù)據(jù)庫連接驅(qū)動mysql-connector-java-5.1.46.jar放在TestJdbc.java所在的目錄下

在此目錄打開cmd命令框,編譯代碼

javac TestJdbc.java

然后在cmd中運行代碼

java -cp mysql-connector-java-5.1.46.jar;. TestJdbc

顯示下面信息則表示連接數(shù)據(jù)庫成功

connect success!
url:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username:root
password:root
driverName:com.mysql.jdbc.Driver

也可以編輯run.bat快捷測試

javac TestJdbc.java
java -cp mysql-connector-java-5.1.46.jar;. TestJdbc
pause

需要測試其他的數(shù)據(jù)庫,只需更換數(shù)據(jù)庫驅(qū)動jar和數(shù)據(jù)庫配置即可.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容