JDBC访问数据库的一般步骤:
注册驱动,获取连接,获取Statement,执行SQL并返回结果集,遍历结果集显示数据,释放连接。
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
// 注册 MySQL 驱动. 也可以使用下面两种方式的任一种
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//new com.mysql.jdbc.Driver();
//Class.forName("com.mysql.jdbc.Driver").newInstance();
// 获取数据库连接。 三个参数分别为 连接URL,用户名,密码
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseWeb", "root", "mysql");
// 获取 Statement。 Statement 对象用于执行 SQL。相当于控制台。
stmt = conn.createStatement();
// 使用 Statement 执行 SELECT 语句。返回结果集。
rs = stmt.executeQuery("select * from tb_person");
while (rs.next()) {
out.println("...");
}
}catch(SQLException e){
out.println("发生了异常:" + e.getMessage());
e.printStackTrace();
}finally{
// 关闭
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(conn != null)
conn.close();
}
常见的数据库连接:
MySQL: | jdbc:mysql://localhost:3306/db |
Oracle: | jdbc:oracle:thin:@localhost:1521/db |
DB2: | jdbc:db2://localhost:6789/db |
PostgreSQl: | jdbc:postgresql://localhost:5432/db |
Sybase:jdbc: | jtds:sybase://localhost:2638/db |
SQLServer: | jdbc:microsoft:sqlserver://localhost:1433;databaseName=db |
SQLServer 2005: | jdbc:sqlserver://localhost:1433;databaseName=db |