使用 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();
}
} }

最新文章

  1. 数据库mysql 基本命令
  2. JavaScript的面向对象编程(OOP)(二)——原型
  3. PyQt写的五子棋
  4. puppet的配置
  5. Java 集合系列02之 Collection架构
  6. JS中 toString() &amp; valueOf()
  7. 题目要求:建立一个类Str,将一个正整数转换成相应的字符串,例如整数3456转换为字符串&quot;3456&quot;.
  8. svn 常用控制台命令解析
  9. MVC3+EF4.1学习系列(九)-----EF4.1其他的一些技巧的使用
  10. myeclipse2015复制项目需要修改的地方
  11. dotNet Linux 学习记录 - Jexus寄宿WCF服务
  12. hbase+springboot+redis实现分页
  13. Liveness 探测 - 每天5分钟玩转 Docker 容器技术(143)
  14. go打造以太坊合约测试框架
  15. if(){}使用
  16. Linux 常用命令 | mkdir/rmdir/touch 的使用
  17. bitcoin双花
  18. Python3学习之路~2.1 列表、元组操作
  19. VS2017仅我的代码警告
  20. CF1111E Tree 树链剖分,DP

热门文章

  1. sortable结合angularjs实现拖动排序
  2. iphone手机QQ浏览器到底部继续上滑出现黑色背景盖住position:fixed的页面元素的问题
  3. 判断是pc端登录还是移动端登录
  4. vue——踩坑
  5. 022 Generate Parentheses 生成括号
  6. Spring Cloud Ribbon负载均衡
  7. MVC学习6 学习使用Code First Migrations功能 把Model的更新同步到DB中
  8. 数据库用户被锁怎么办,报the passord logon
  9. [JQuery] Using skill in JQuery
  10. 数据库查询SQL语句的时候如何写会效率更高?