import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;/** * JDBC 串連 MySQL 資料庫 * * @author zhanqi * */public class MySQL { private static String driver = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/資料庫名"; public static void main(String[] args) { Connection ct = null; PreparedStatement ps = null; ResultSet rs = null; try { // 載入驅動類 Class.forName(driver); // 得到串連 ct = DriverManager.getConnection(url, "root", "root"); // 得到先行編譯的 SQL 陳述式的對象 ps = ct.prepareStatement("select count(*) from 表名"); // 得到結果集 rs = ps.executeQuery(); // 迴圈取出記錄 while (rs.next()) { System.out.println(rs.getInt(1)); } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉資源 try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (ct != null) { ct.close(); } } catch (Exception e) { e.printStackTrace(); } } }}
附:
- MySQL Community Server 5.5: 下載
- MySQL jdbc driver 5.1:下載