连接数据库步骤:
1. 注册驱动(只做一次)
2. 建立连接(Connection)
3. 创建执行SQL的语句(Statement)
4. 执行语句
5. 处理执行结果(ResultSet)
6. 释放资源
举例:
public void connectionOracle() throws SQLException{
Connection conn = null; // 数据库连接
PreparedStatement ps = null; // 预编译语句对象
ResultSet rs = null; // 结果集对象
try {
// 注册(加载)Oracle驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
// Class.forName("com.mysql.jdbc.Driver");注册(加载)mysql驱动
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
//String url = "jdbc:mysql://127.0.0.1:3306/mybatis";
//String url = "jdbc:mysql://localhost:3306/mybatis";
String user = "scott";
String password = "tiger";
conn = DriverManager.getConnection(url, user, password);
String sql = "select ename from emp where job ='CLERK'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
System.out.println("ename is : " + rs.getString("ename"));
}
System.out.println("End@@@");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try { if (rs != null) {rs.close();}}
finally {
try {if (ps != null) {ps.close();}}
finally {if (conn != null) {conn.close();}
}
}
}
}
如果sql="select count(*) from items";
则使用时
while(rs.next()){
System.out.println(rs.getInt(1));
}