JDBC学习一 基础 一个简单的增删该查例子

jdbcUtil02.java

 

//单例模式
public final class jdbcUtil02 {
 static String url = "jdbc:mysql://localhost:3306/jdbc";
 static String username = "root";
 static String password = "root";
 
 //private static jdbcUtil02 instance = new jdbcUtil02();
 private static jdbcUtil02 instance= null;
 //构造私有化
 private jdbcUtil02(){
  
 }
 
 //提供一个公共的static方法
 public static jdbcUtil02 getInstance(){
  if (instance==null) {
   //延迟加载  使用的时候new
   //处理并发问题  可以加锁
   synchronized (jdbcUtil02.class) {
    instance = new jdbcUtil02();
   }
  }
  return instance;
 }
 
 public static Connection getConnection() throws SQLException {
  return DriverManager.getConnection(url, username, password);
 }
 
 public static void free(Statement st, Connection conn, ResultSet rs) {
  try {
   if (rs != null) {
    rs.close();
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    if (conn != null) {
     conn.close();
    }
   } catch (SQLException e2) {
    e2.printStackTrace();
   } finally {
    try {
     if (st != null) {
      st.close();
     }
    } catch (SQLException e2) {
     e2.printStackTrace();
    }
   }
  }
 }
}

 

 

package com.sg.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.Test;

public class JdbcCRUDTest {
 // 查询
 @Test
 public void select() throws Exception {
  Connection conn = jdbcUtil02.getInstance().getConnection();
  Statement st = conn.createStatement();
  ResultSet rs = st.executeQuery("select * from user");

  while (rs.next()) {
   System.out.println("id:" + rs.getInt("id") + "\n name:"
     + rs.getString("name") + "\n age:" + rs.getInt("age")
     + "\n sex" + rs.getString("sex") + "\n brithday:"
     + rs.getDate("brithday"));
  }
  // 关闭资源
  jdbcUtil02.free(st, conn, rs);
 }
 //添加
 @Test
 public void insert() throws Exception {
  Connection conn = jdbcUtil02.getInstance().getConnection();
  Statement st = conn.createStatement();
  String sql = "insert into user values(4,'name1',20,'nan','1992-12-28')";
  int i = st.executeUpdate(sql);
  System.out.println("i = "+i);
  
 }
 //修改
 @Test
 public void update() throws Exception {
  Connection conn = jdbcUtil02.getInstance().getConnection();
  Statement st = conn.createStatement();
  String sql = "update user set age = 30 where id = 1";
  int i = st.executeUpdate(sql);
  
 }
 //删除
 @Test
 public void delete() throws Exception {
  Connection conn = jdbcUtil02.getInstance().getConnection();
  Statement st = conn.createStatement();
  String sql = "delete from user where id > 2";
  int i = st.executeUpdate(sql);
  
 }
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值