怎么用java连接oracle数据库,需要详细解释

2024-12-02 04:36:13
推荐回答(3个)
回答1:

1)首先你要有java连接oracle数据库的驱动类,下载好后导入到工程里

2)代码:
import java.sql.*;

public class JDBCTest {

/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args)
throws ClassNotFoundException, SQLException{
//1.准备参数
String ip = "192.168.0.26";
String sid = "tarena";
String port = "1521";
String dbUser = "openlab";
String dbPassword = "open123";
String driver
= "oracle.jdbc.driver.OracleDriver";

//2.构造驱动实例
Class.forName(driver);

//3.创建连接
//连接字符串是固定的形式,oracle的形式:
String url
= "jdbc:oracle:thin:@"
+ ip + ":" + port + ":" + sid;
Connection conn
= DriverManager.getConnection
(url, dbUser, dbPassword);
//4.执行SQL语句
String sql = "select id, password, name from user_sd1104 " +
"where id = 1001 and password = '1234'";
Statement stmt = conn.createStatement();
ResultSet rs
= stmt.executeQuery(sql);//执行sql语句
while(rs.next()){
int id = rs.getInt(1);
String pwd = rs.getString(2);
String name = rs.getString(3);
System.out.println("welcome," + name);
}
rs.close();
stmt.close();
conn.close();
}

}

回答2:

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@主机名:端口号:数据库名";//

String user = "xxxt";//登录数据库的用户名
String password = "xxx";//密码
try {
con = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
System.out.println("error" + e.getMessage());
}
} catch (Exception e) {
System.out.println("error" + e.getMessage());
}

回答3:

java对各种数据库提供了统一的接口,就像其在不同操作系统之间可以用相同的方式编程一样,由不同的数据库厂商提供自己的数据库驱动,这个要自己下载。总之掌握数据库编程那几个基本方法就行了,每种数据库连接方法都是一样的