首页 > 数据库 >JDBC(MySQL)

JDBC(MySQL)

时间:2022-09-22 23:35:39浏览次数:48  
标签:JDBC String resultSet connection user MySQL close properties

JDBC(MySQL)

​ 使用JDBCUtils的优点,在我们有大量使用mysql的数据库的情况下,我们可以通过更改jdbc.properties配置文件就可以修改数据库的配置,而不是寻找代码然后在一次次更改代码中的数据

properties文件,文件名user.properties

user=pxx
password=123
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/pxx
//通过propertices获取配置文件的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src/JavaTest/day2/user.properties"));
        //获取相关的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //注册驱动,建议写上兼容之前的版本
        Class.forName(driver);
        //得到连接
        Connection connection = DriverManager.getConnection(url, user, password);
        //Mysql语句
        String sql ="insert into students values(?,?,?)";
        //preparedStatement对象实现PreparedStatement接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //给?赋值
        preparedStatement.setInt(1,102192121);
        preparedStatement.setString(2, "彭大旧");
        preparedStatement.setString(3,"男");
        //执行sql语句executeUpdate(),返回影响行数
        // 执行查询语句executeQuery(),返回ResultSet对象,要用while循环,next是指向结果下一行
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            int id = resultSet.getInt(1);  //第一列
            String name = resultSet.getString(2);
            String gender = resultSet.getString(3);
            System.out.println(id + "\t" + name + "\t" +gender);
        }
        // execute()执行任意sql语句返回布尔值

        int row = preparedStatement.executeUpdate();
        System.out.println(row>0?"successful":"fault");
        //关连接
        preparedStatement.close();
        connection.close();

JDBCUtils

public class JDBCUtils {


   private static String url;
   private static String user;
   private static String password;
   private static String driver;

   static {

       try {
           //1. 创建Properties集合类。
           Properties properties = new Properties();

           //获取src路径下的文件的方式--->ClassLoader 类加载器
           ClassLoader classLoader = JDBCUtils.class.getClassLoader();
           URL res  = classLoader.getResource("jdbc.properties");
           String path = res.getPath();
           //2. 加载文件
           properties.load(new FileReader(path));

           url = properties.getProperty("url");
           user = properties.getProperty("user");
           password = properties.getProperty("password");
           driver = properties.getProperty("driver");

           //注册驱动
           Class.forName(driver);


       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }


   }


   /**
    * 获取连接
    * @return 连接对象
    */
   public static Connection getConnection() throws SQLException {

       return DriverManager.getConnection(url, user, password);
   }


   /**
    * 释放资源
    * @param statement
    * @param connection
    */

   public static void close(Statement statement, Connection connection) {
       if (statement != null) {
           try {
               statement.close();
           } catch (SQLException throwables) {
               throwables.printStackTrace();
           }
       }
       if (connection != null) {
           try {
               connection.close();
           } catch (SQLException throwables) {
               throwables.printStackTrace();
           }
       }

   }

   /**
    * 释放资源
    * @param resultSet
    * @param statement
    * @param connection
    */
   public static void close(Statement statement, Connection connection,ResultSet resultSet) {
       if (resultSet != null) {
           try {
               resultSet.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }

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

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

   }

}



/**
* JDBCUtils的测试类
* 
*/
public class JDBCUtilsDemo {

   public static void main(String[] args) {

       List<student> students = new JDBCUtilsDemo().finAll();
       System.out.println(students);
       System.out.println(students.size());

   }

   public List<student> finAll() {

       Connection connection = null;
       PrepareStatement prepareStatement = null;
       ResultSet resultSet = null;
       String sql = "SELECT * from student where id = ?";

       try {

           //1. 导入驱动jar包 mysql-connector-java-5.1.37-bin.jar
           //2. 注册驱动
           //以上2步骤都通过JDBCUtils来简化了
           connection=JDBCUtils.getConnection();
           //3.获取执行sql的对象
           prepareStatement = connection.prepareStatement(sql);
           prepareStatement.setInt(1,102)
           //4.执行sql
           resultSet = prepareStatement.executeQuery();
           //5.遍历结果集,封装对象,装载集合
           student stu = null;
           list = new ArrayList<student>();
           while (resultSet.next()) {
               int id = resultSet.getInt("id");
               String ename = resultSet.getString("name");
               System.out.println(id + "\t" + name + "\t");
           }

       } catch (SQLException throwables) {
           throwables.printStackTrace();
       } finally {
           JDBCUtils.close(statement,connection,resultSet);
       }
       
   }
}

标签:JDBC,String,resultSet,connection,user,MySQL,close,properties
From: https://www.cnblogs.com/pxxxxp/p/16721195.html

相关文章

  • MySQL数据库导入导出数据
    导出数据:mysqldump-hIP-u用户名-p数据库名>导出的文件名比如:mysqldump-hlocalhost-uroot-pstudent>login.sql导入数据:use数据库;source导出的文件名......
  • MySQL学习笔记
    create 命令创建数据库,语法如下:CREATEDATABASE数据库名;drop命令删除数据库drop命令格式:dropdatabase<数据库名>;数据类型:MySQL支持多种类型,大致可以分为三类......
  • navicat解密mysql
    先获取mysql加密密码,在使用php解密程序解出密码,1.使用navicat导出连接,文件中有加密密码,2.在注册表中,计算机\HKEY_CURRENT_USER\SOFTWARE\PremiumSoft\Navicat\Servers\{连......
  • MySQL及MySQL Workbench下载与安装
     安装MySQLWorkbench参考链接:https://blog.csdn.net/qq_51813155/article/details/121705128一、下载MSI文件下载地址:https://dev.mysql.com/downloads/workbench/......
  • MySQL日期类型介绍及格式化
    1、MySQL中常用的几种时间类型有:date、datetime、time、year、timestamp数据类型占用字节最小值最大值零值表示备注date41000-01-019999-12-310000-00-0......
  • MySQL InnoDB 锁的二三事
    近日, 在一个小型项目中, 遇到了一个触及我知识盲区的bug. 项目用的是MySQL5.7.25, 其中有一张表 config_data,包含四个字段,id,name,value,expireAt.其中id......
  • 脚本二进制编译安装Mysql
    mysql二进制安装脚本部署目录mysql二进制安装脚本部署单实例使用函数的单实例使用函数的单实例或者多实例单实例[root@localhost~]#mkdirmysql//创建存......
  • centos6创建mysql开机自启动
    环境:OS:centos6db:5.6.40 1.修改/etc/init.d/mysqld文件,默认文件以及存在,该文件内容如下:#!/bin/sh#CopyrightAbandoned1996TCXDataKonsultAB&MontyPro......
  • MySQL中datetime和timestemp类型23:59:59秒入库后会变成下一天的00:00:00
    1.问题现象业务中需要记录一个价格的生效时间和失效时间,对应的是MySQL表中的datetime类型。前端传入的失效时间是日期,如2022-09-2023:59:59,在java程序中时间也是正确......
  • JavaWeb--MySql基础:数据库概念、MySql前期基础、SQL基础语句、Navicat使用--2022年9月
    第一节  数据库1、数据库是什么存储和管理数据的仓库,数据是有组织的进行存储。数据库英文名是DataBase,简称DB2、数据库管理系统......