JDBC 连接 MySQL 数据库
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(); } } } }
附: