连接数据库步骤:
- 注册驱动
- 获取数据库连接
- 创建数据库操作对象用于执行SQL
- 执行语句
- 处理执行结果
- 释放资源
import java.sql.*;
public class test {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL1", "system", "test");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from emp");
while (rs.next()) {
System.out.println(rs.getString("empno"));
System.out.println(rs.getString("ename"));
System.out.println(rs.getString("deptno"));
System.out.println(rs.getInt("sal"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}