2022-05-12 08:17:49
浏览数 (1)
1、DBUtil类
代码语言:javascript
复制package tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* JDBC连接Oracle数据库的示例代码
* @author:yunfan
* */
public class DBUtil{
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();// 加载Oracle驱动程序
System.out.println("oracle驱动程序加载中!");
}
catch(InstantiationException e1)
{
System.out.println("实例异常");
}
catch(IllegalAccessException e2)
{
System.out.println("访问异常");
}
catch(ClassNotFoundException e3)
{
System.out.println("MySQL驱动类找不到");
}
}
/***
* 返回一个数据库连接
*/
public static Connection getConnection()
{
Connection connection = null;// 创建一个数据库连接
try
{
System.out.println("开始尝试连接数据库!");
String url = "jdbc:oracle:thin:@127.0.0.1:1521:oracle";//Oracle的默认数据库名
String user = "system";// 系统默认的用户名
String password = "system";// 安装时设置的密码
connection = DriverManager.getConnection(url, user, password);// 获取连接
System.out.println(url);
System.out.println("用户名:" user "t" "密码:******");
System.out.println("数据库连接成功!");
return connection;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
2、ConnectTest类
代码语言:javascript
复制package tools;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnectTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet result = null;
try {
connection = DBUtil.getConnection();
String sql = "select * from user where id = ?";
ps = connection.prepareStatement(sql);
ps.setInt(1, 1);
result = ps.executeQuery();
while (result.next()) {
System.out.println(result.getInt("id") " 用户名:"
result.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
// 注意关闭的顺序,最后使用的最先关闭
if (result != null) {
result.close();
}
if (ps != null) {
ps.close();
}
if (connection != null) {
connection.close();
}
System.out.println("数据库连接已关闭!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
控制台输出:
代码语言:javascript
复制oracle驱动程序加载中!
开始尝试连接数据库!
jdbc:oracle:thin:@127.0.0.1:1521:oracle
用户名:system 密码:******
数据库连接成功!
1 用户名:yunfan
数据库连接已关闭!