Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Created December 27, 2015 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/3ce9919a93f771e034d4 to your computer and use it in GitHub Desktop.
Save Cartman0/3ce9919a93f771e034d4 to your computer and use it in GitHub Desktop.
JDBCドライバでMySQLのDBにアクセス
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* データベース接続クラス
*/
public class DbConnect {
public static void main(String[] args) {
Connection connection_mysql = null;
try {
/* JDBCドライバのロード
* 「com.mysql.jdbc.Driver」クラス名
* JDBC4以降ではClass.forName必要なし
* http://www.ne.jp/asahi/hishidama/home/tech/java/DriverManager.html
* Class.forName("com.mysql.jdbc.Driver");
*/
/*
* データベースと接続
* 「ライブラリの追加」で「MySQL JDBCドライバ」を追加しておく
*/
connection_mysql = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample", "user_name", "password");
// 接続しているデータベース名を表示
System.out.println("MySQLに接続できました。");
System.out.println("getCatalog: " + connection_mysql.getCatalog());
} /*catch(ClassNotFoundException ce) {
// JDBCドライバが見つからなかった場合
ce.printStackTrace();
} */ catch (SQLException se) {
// データベースとの接続に失敗した場合
se.printStackTrace();
} finally {
try {
// データベースとの接続を解除
if (connection_mysql != null) {
connection_mysql.close();
}
} catch (SQLException se) {
// データベースとの接続解除に失敗した場合
se.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment