url路径就是jdbc:oracle:@+主机的ip地址(本机数据库就可以用localhost):加端口号:加数据库名字
package com.jdbc.testimport 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:1433databaseName=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()
}
}
}
这是以前写的3中数据库的链接已经测试过了。
1、工作环境:myeclipse中->新建java_oracle工程->新建包com.zp->新建java_oracle_jdbc.java类2、需要配置Oracle数据库驱动
java工程(java_oracle)—>右键属性(Properties)->Java Build Path->Libraries->Add External JARs->添加oracle安装目录E:\oracle\product\10.1.0\Db_1\jdbc\lib下的“classes12.jar”文件;
每次新建一个不同工程都需要配置一次
3、代码如下:
package com.zp
import java.sql.*
public class java_oracle_jdbc {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver")
//得到连接
Connection ct=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:simlink", "scott", "tiger")
Statement sm=ct.createStatement()
ResultSet rs=sm.executeQuery("select * from emp")
while(rs.next())
{
System.out.println("用户名:"+rs.getString(2))
}
rs.close()
sm.close()
ct.close()
}
catch(Exception e)
{
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)