JDBCを利用してMySQLに接続するには 1. MySQLをセットアップします。
2. MySQL JDBC Driverを取得します。
3. .jarファイルにclasspathを通します。
4. 以下のようにコードを書き実行します。
日本語をShift-JISで扱うには、別にcharactor-set = Shift-JISを設定してやる必要があります。
// Sample application for JDBC connection to MySql import
import java.sql.*;
public class JdbcTest
{
public static void main(String[] args)
{
try
{
// Loading driver class
Class.forName("org.gjt.mm.mysql.Driver"); // MySQL
// Connect to the database
Connection con =
// only for MySQL
DriverManager.getConnection("jdbc:mysql://localhost/person", "username", "password");
// Create a statement object
Statement stmt = con.createStatement();
String sql = "SELECT * FROM employee";
// Execute the query and get a result
ResultSet rs = stmt.executeQuery(sql);
// Loop with the number of found data
while(rs.next())
{
// Id
int id = rs.getInt("id");
// name
String name = rs.getString("name");
// birthday
String birthday = rs.getString("birthday");
// memo
String memo = rs.getString("memo");
// Desplay data
System.out.println(id + " " + name + " " + birthday + " " + memo);
}
// Disconnect from the database
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
目次に戻る
| Copyright(c) 2008 WoodenSoldier Software |
|