2009年12月9日水曜日

JDBCドライバの接続確認

JDBCドライバとMySQLの接続テスト


public class Dbconnect {
public static void main(String args[]) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/データベース名", "root", "パスワード入力");
System.out.println("MySQL と接続しました。");
} catch (SQLException e) {
System.out.println("MySQL との接続失敗");
System.out.println("SQLExceptionは " + e.getMessage());
System.out.println("SQLStateは " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
conn = null;
System.out.println("MySQLとの接続を切断しました");
}
} catch (Exception e) {
}
}
}
}