JAVA JDBC 连接 Oracle
2024-09-29 14:46:09
使用 Junit 测试类编写
public class JdbcTest {
private Connection con = null;// 创建一个数据库连接
private PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
private ResultSet result = null;// 创建一个结果集对象
@Before
public void init(){
try {
System.out.println("创建数据库连接...");
Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
String url = "jdbc:oracle:" + "thin:@127.0.0.1:1521:orcl";// 127.0.0.1是本机地址,ORCL 是Oracle的数据库名字
Properties po = new Properties();
po.put("user", "***");
po.put("password", "*****");
con = DriverManager.getConnection(url,po);// 获取连接
System.out.println("数据库连接成功!");
} catch (Exception e) {
System.out.println("数据连接失败!");
e.printStackTrace();
}
}
@Test
public void select() {
try {
String sql = "select * from t_product";// 预编译语句,“?”代表参数
pre = con.prepareStatement(sql);// 实例化预编译语句
result = pre.executeQuery();// 执行查询(select使用),注意括号中不需要再加参数
ArrayList<TProduct> productsList = new ArrayList<TProduct>();
while (result.next()){
// 当结果集不为空时
TProduct product = new TProduct(result.getInt("product_id"), result.getString("product_name"), result.getDouble("product_price"));
productsList.add(product);
}
System.out.println(productsList);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Test
public void update(){
try {
String sql = "update t_product set product_name = ? where product_id = ?";
pre = con.prepareStatement(sql);
pre.setString(1, "可口可乐");
pre.setInt(2, 0);
if(pre.executeUpdate() == 1) //update, delete, insert, 使用 executeUpdate()
System.out.println("update successful!");
else
System.out.println("update fail!");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@After
public void end(){
//不管如何,连接的对象必须释放
try
{
// 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
// 注意关闭的顺序,最后使用的最先关闭
if (result != null)
result.close();
if (pre != null)
pre.close();
if (con != null)
con.close();
System.out.println("数据库连接已关闭!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
最新文章
- 数据库mysql 基本命令
- JavaScript的面向对象编程(OOP)(二)——原型
- PyQt写的五子棋
- puppet的配置
- Java 集合系列02之 Collection架构
- JS中 toString() &; valueOf()
- 题目要求:建立一个类Str,将一个正整数转换成相应的字符串,例如整数3456转换为字符串";3456";.
- svn 常用控制台命令解析
- MVC3+EF4.1学习系列(九)-----EF4.1其他的一些技巧的使用
- myeclipse2015复制项目需要修改的地方
- dotNet Linux 学习记录 - Jexus寄宿WCF服务
- hbase+springboot+redis实现分页
- Liveness 探测 - 每天5分钟玩转 Docker 容器技术(143)
- go打造以太坊合约测试框架
- if(){}使用
- Linux 常用命令 | mkdir/rmdir/touch 的使用
- bitcoin双花
- Python3学习之路~2.1 列表、元组操作
- VS2017仅我的代码警告
- CF1111E Tree 树链剖分,DP
热门文章
- sortable结合angularjs实现拖动排序
- iphone手机QQ浏览器到底部继续上滑出现黑色背景盖住position:fixed的页面元素的问题
- 判断是pc端登录还是移动端登录
- vue——踩坑
- 022 Generate Parentheses 生成括号
- Spring Cloud Ribbon负载均衡
- MVC学习6 学习使用Code First Migrations功能 把Model的更新同步到DB中
- 数据库用户被锁怎么办,报the passord logon
- [JQuery] Using skill in JQuery
- 数据库查询SQL语句的时候如何写会效率更高?