实现步骤
1.加载驱动
Class.forName("oracle.jdbc.OracleDriver");
2.获取连接对象
Connection connection = DriverManager
.getConnection("jdbc:oracle:thin:@localhost:1521/XE", "scott", "tiger");
3.获取sql执行环境
Statement st = connection.createStatement();
4.执行sql语句
ResultSet resultSet = st.executeQuery(sql);
5.关闭连接对象
st.close();
connection.close();
完整代码如下:
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1、加载驱动
Class.forName("oracle.jdbc.OracleDriver");
//2、获取数据库连接对象
Connection connection = DriverManager
.getConnection("jdbc:oracle:thin:@localhost:1521/XE", "scott", "tiger");
//3、获取sql执行环境
Statement st = connection.createStatement();
//4、执行sql语句
String sql = "select * from emp";
ResultSet resultSet = st.executeQuery(sql);
while(resultSet.next()){
System.out.print(resultSet.getInt("empno") + " ");
System.out.println(resultSet.getString("ename"));
}
//5、释放资源,关闭连接对象
st.close();
connection.close();
}
}