请写出一段JDBC访问Oracle数据库的代码
发布网友
发布时间:2022-04-07 20:29
我来回答
共2个回答
热心网友
时间:2022-04-07 21:59
实现思路:就是通过ojdbc.jar中提供的方法,直接连接数据库即可,固定代码写法如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCTest {
public static void main(String[] args) throws Exception {
//1.加载驱动
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Class.forName("com.mysql.jdbc.Driver");
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.创建数据库连接对象
//Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=db","sa","sqlpass");
//Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8","root","123456");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","Oracle123");
//3.创建数据库命令执行对象
Statement stmt = conn.createStatement();
//PreparedStatement ps = conn.prepareStatement("select * from t_user");
//4.执行数据库命令
ResultSet rs = stmt.executeQuery("select * from t_user");
//ResultSet rs = ps.executeQuery();
//5.处理执行结果
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println(id + "\t" + username + "\t" + password);
}
//6.释放数据库资源
if (rs != null) {
rs.close();
}
//if (ps != null) {
//ps.close();
//}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
}
热心网友
时间:2022-04-07 23:17
给你个实例吧,但要真弄明白,恐怕还是得自己独立做成一次:
Connection conn=DriverManager.getConnection("","","");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("");