JDBC

一.JDBC连接数据库的方式

1.

    public void test1() throws SQLException {
       //获取Driver的实现类对象
       Driver driver=new com.mysql.cj.jdbc.Driver();
//指明需要连接的数据库
       String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
       //将用户名密码封装在properites中
       Properties info=new Properties();
       info.setProperty("user","root");
       info.setProperty("password","abc123");
       //获取连接
     Connection conn= driver.connect(url,info);
       System.out.println(conn);
  }

2.通过反射

 public void test2() throws Exception {
       //1.获取Driver实现类对象:使用反射
      Class clazz= Class.forName("com.mysql.cj.jdbc.Driver");
       Driver driver = (Driver) clazz.newInstance();
       //2.提供要连接的数据库
       String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
       //3.提供连接需要的用户名和密码
       Properties info=new Properties();
       info.setProperty("user","root");
       info.setProperty("password","abc123");
       //4.获取连接
       Connection conn= driver.connect(url,info);
       System.out.println(conn);
  }

3.通过DriverManager 替换Driver

    public void test3() throws SQLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
       //方式三:使用DriverManager替换Driver
      //获取三个连接的基本信息
       String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
       String user="root";
       String password="abc123";
       //新版本已经不需要注册驱动,注册驱动被封装在获取连接中
//       Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
//       Driver driver= (Driver) clazz.getDeclaredConstructor().newInstance();
//       //注册驱动
//       DriverManager.registerDriver(driver);
       //获取连接
       Connection conn = DriverManager.getConnection(url, user, password);
       System.out.println(conn);

  }

4.对方式三的优化

    public void test4() throws Exception {
       //方式四:对方式三的优化
       //1.获取三个连接的基本信息
       String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
       String user="root";
       String password="abc123";
       //2.加载Driver
       //新版本已经不需要注册驱动,注册驱动被封装在获取连接中
Class.forName("com.mysql.cj.jdbc.Driver");
//       Driver driver= (Driver) clazz.getDeclaredConstructor().newInstance();
//       //注册驱动
//       DriverManager.registerDriver(driver);
       //3.获取连接
       Connection conn = DriverManager.getConnection(url, user, password);
       System.out.println(conn);
  }

5.最终版

    public void test5() throws Exception {
       //方式五:最终版
       //将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式获取连接
       //1.读取配置文件中的4个基本信息
       //通过类的加载器
       InputStream is = ConnectTest.class.getClassLoader().getResourceAsStream("JDBC.properties");
       Properties pro=new Properties();
       pro.load(is);
       String user = pro.getProperty("user");
       String password=pro.getProperty("password");
      String  driver = pro.getProperty("driver");
       String url = pro.getProperty("url");
       //2.加载驱动
        Class.forName(driver);
        //3.获取连接
       Connection conn = DriverManager.getConnection(url, user, password);
       System.out.println(conn);

  }

 

二.PrepareStatement实现修改数据库

1.增删改 PrepareStatement.execute();

    //向customers表中添加一条记录
   @Test
   public void testInsert() {
       //连接数据库
       Connection conn = null;
       PreparedStatement ps = null;
       try {
           InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("JDBC.properties");
           Properties pro =new Properties();
           pro.load(is);
           String user = pro.getProperty("user");
           String url = pro.getProperty("url");
           String password = pro.getProperty("password");
           String driver = pro.getProperty("driver");
           Class.forName(driver);
           conn = DriverManager.getConnection(url,user,password);
//       System.out.println(conn);
           //预编译sql语句,返回PrepareStatement实例
           String sql="insert into customers(name,email,birth) values(?,?,?)"; // ?占位符
           ps = conn.prepareStatement(sql);
           //填充占位符
           ps.setString(1,"哪吒");
           ps.setString(2,"nezha@.com");
           SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
           java.util.Date date = sdf.parse("1000-01-01");
           ps.setDate(3,new Date(date.getTime()));
           //执行操作
           ps.execute();
      } catch (IOException e) {
           e.printStackTrace();
      } catch (ClassNotFoundException e) {
           e.printStackTrace();
      } catch (SQLException e) {
           e.printStackTrace();
      } catch (ParseException e) {
           e.printStackTrace();
      } finally {
           //资源的关闭
           if (ps != null) {

               try {
                   ps.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
          }
           if (conn != null) {
               try {
                   conn.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
          }
      }
  }

2.查 PrepareStatement.executeQuery()

package PreparedStatement;

/**
* <h5>描述:</h5>
*/

import Bean.Customers;
import Utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.sql.*;

/**
* @Description 针对Customers表的查询操作
*/
public class CustomersForQuery {
   @Test
   public void testQueryForCustomers() {
       String sql="select id,name,email,birth from customers where id=?";
       Customers customers = queryForCustomers(sql, 13);
       System.out.println(customers);
  }
   /**
    * @Description 针对与Customers这个表查询的通用操作
    */
   public Customers queryForCustomers(String sql,Object...args) {
       Connection conn=null;
       Customers cus= null;
       PreparedStatement ps=null;
       ResultSet rs=null;
       try {
            conn = JDBCUtils.getConnection();
           ps = conn.prepareStatement(sql);
           for (int i = 0; i < args.length; i++) {
               ps.setObject(i+1,args[i]);
          }
            rs = ps.executeQuery();
           //获取结果集的元数据resultset.getmetadata();
           ResultSetMetaData rsmd = rs.getMetaData();
           //通过ResultSetMetaData获取结果集中的列数
           int columnCount = rsmd.getColumnCount();
           cus = null;
           if (rs.next()) {
               cus=new Customers();
               //处理一行数据中的每一个列
               for (int i = 0; i < columnCount; i++) {
                   //获取列值
                   Object value = rs.getObject(i + 1);
                   //获取每个列的列名字
                   String columnName = rsmd.getColumnName(i+1);
                   //给cus对象的指定属性赋值为value
                   Field field = Customers.class.getDeclaredField(columnName);
                   field.setAccessible(true);
                   field.set(cus,value);
              }
          }
      } catch (Exception e) {
           e.printStackTrace();
      }
       finally {
           JDBCUtils.closeResource(conn,ps,rs);
      }
       return cus;
  }

   @Test
   public void testQuery1() {
       Connection conn = null;
       PreparedStatement preparedStatement = null;
       ResultSet resultSet = null;
       try {
           conn = JDBCUtils.getConnection();
           String sql="select id,name,email,birth from customers where id=?";
           preparedStatement = conn.prepareStatement(sql);
           preparedStatement.setInt(1,1);

           //执行并返回结果集
           resultSet = preparedStatement.executeQuery();
           //处理结果集
           if (resultSet.next()){//判断结果集的下一条是否有数据,如果返回true,指针下移,如果没有,退出
               //获取当前这条数据的各个字段值
               int id = resultSet.getInt(1);
               String name = resultSet.getString(2);
               String email = resultSet.getString(3);
               Date birth = resultSet.getDate(4);
               //方式一:直接显示
              //方式二:封装在一个数组中
  //             Object[]data=new Object[]{id,name,email,birth};
              //方式三: 封装在一个类的对象中
               Customers customer=new Customers(id,name,email,birth);
               System.out.println(customer);
          }
      } catch (Exception e) {
           e.printStackTrace();
      } finally {
           //关闭资源
           JDBCUtils.closeResource(conn,preparedStatement,resultSet);
      }

  }
}

三.ORM编程思想

 * OMR编程思想(Object relational mapping)
* 一个数据表对应一个java类
* 表中的一条记录对应java类的一个对象
* 表中的一个字段对应java类的一个属性
public class CustomersForQuery {
@Test
public void testQueryForCustomers() {
String sql="select id,name,email,birth from customers where id=?";
Customers customers = queryForCustomers(sql, 13);
System.out.println(customers);
}
/**
* @Description 针对与Customers这个表查询的通用操作
*/
public Customers queryForCustomers(String sql,Object...args) {
Connection conn=null;
Customers cus= null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据resultset.getmetadata();
ResultSetMetaData rsmd = rs.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
cus = null;
if (rs.next()) {
cus=new Customers();
//处理一行数据中的每一个列
for (int i = 0; i < columnCount; i++) {
//获取列值
Object value = rs.getObject(i + 1);
//获取每个列的列名字
String columnName = rsmd.getColumnName(i+1);
//给cus对象的指定属性赋值为value
Field field = Customers.class.getDeclaredField(columnName);
field.setAccessible(true);
field.set(cus,value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
JDBCUtils.closeResource(conn,ps,rs);
}
return cus;
}
   public Order orderForQuery(String sql,Object...args)  {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args .length; i++) {
ps.setObject(i+1,args[i]);
}


//执行,获取结果集
rs = ps.executeQuery();
//获取结果集的元数据
ResultSetMetaData rsmd = rs.getMetaData();
//获取列数
int columnCount = rsmd.getColumnCount();
Order order=null;
if (rs.next()) {
for (int i = 0; i < columnCount; i++) {
//获取每个列的列值:通过ResultSet
Object columnValue = rs.getObject(i + 1);
//获取每个列的列名:通过ResultMetaData---------不推荐使用
//获取每个列的别名:通过ResultMetaData
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = Order.class.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(order,columnValue);
}
return order;
}
} catch (Exception e) {
e.printStackTrace();
} finally {

JDBCUtils.closeResource(conn,ps,rs);
}
return null;
}

在查询中,使用ResultSetMetaData推荐使用 ColumnLaber替换ColumnName

这样的话如果存在数据库表中的列明和javaBean中的属性名不一样时,sql语句中可以使用列的别名,对应ColumnLaber

 

四.Druid数据库连接池

    public void getConnection() throws Exception {
//1.读取配置文件
Properties pr = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("Druid.properties");
pr.load(is);
//2.使用工厂创建source
DataSource source = DruidDataSourceFactory.createDataSource(pr);
//3.通过source获取连接
Connection conn = source.getConnection();
System.out.println(conn);
}


posted @ 2022-05-14 19:42  与否业务NOW  阅读(44)  评论(0)    收藏  举报