JDBC学习(二)---将JDBC优化为工具包/数据库的增删改查

news/2024/5/19 0:27:36 标签: JDBC

JDBCJDBC_0">JDBC学习(二)—将JDBC优化为工具包/数据库的增删改查

JDBC_2">01 JDBC的优化

为了优化对JDBC的使用,避免代码的重复率,将创建JDBC的繁琐过程简化为工具包中的各个方法。具体步骤如下:

  • 新建配置文件:内容包括创建连接时所需的驱动,数据库的用户名和密码,以及url

    • 在src下建立db.properties,内容如下
    driver = com.mysql.jdbc.Driver
    username = root
    password = 123456
    url = jdbc:mysql://localhost:3306/jdbcstudy?useSSL=true
    
  • 在src下新建包,这里命名为utils,在该包下新建类,这里命名为JDBCUtiles

    • 注意事项:为了方便使用,工具包的成员变量和方法一般采用static修饰
    package com.hooi.utils;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    
    public class JDBCUtils {
        public static String driver=null;
        public static String username=null;
        public static String password=null;
        public static String url=null;
    
        static {
    
            try {
                //以输入流的形式加载配置文件
                InputStream stream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
                Properties properties = new Properties();
                properties.load(stream);
                //读取配置文件
                driver = properties.getProperty("driver");
                username = properties.getProperty("username");
                password = properties.getProperty("password");
                url = properties.getProperty("url");
                //加载数据库驱动
                Class.forName(driver);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        //获取数据库连接
        public static Connection getConnect() throws SQLException {
            return DriverManager.getConnection(url,username,password);
        }
    
        //释放资源
        public static void closeAll(ResultSet resultSet, Statement statement,Connection connection){
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    

02 数据库的增删改查

为了方便测试,这里引入Junit。Junit的导包十分方便,在IDEA类的编辑界面输入:@Test,第一次使用Junit该语句会报红,按alt+enter选择add 'Junit4'to classpath,IDEA会自动下载Junit并且导入lib目录

package com.hooi.demo;

import com.hooi.utils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class TestDemo {

    @Test
    public void insert() {


        Connection connection = null;
        Statement statement = null;

        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();
            //3.编写Sql语句
            String sql = "INSERT INTO users(id,NAME,PASSWORD,email,birthday) VALUES(5,'wangwu','123456','wangwu@sina.com','1979-12-04');";
            //4.执行sql语句
            int i = statement.executeUpdate(sql); //返回受影响的行数
            //5.查看结果
            System.out.println("增加了"+i+"行数据");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            JDBCUtils.closeAll(null,statement,connection);
        }

    }

    @Test
    public void delete() {

        Connection connection = null;
        Statement statement = null;

        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();
            //3.编写Sql语句
            String sql = "delete from users where id = 4";
            //4.执行sql语句
            int i = statement.executeUpdate(sql); //返回受影响的行数
			//5.查看结果
            if (i>0){
                System.out.println("删除成功");
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            JDBCUtils.closeAll(null,statement,connection);
        }

    }

    @Test
    public void update() {

        Connection connection = null;
        Statement statement = null;

        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();
            //3.编写Sql语句
            String sql = "update users set name = 'lily' where id = 4";
            //4.执行sql语句
            int i = statement.executeUpdate(sql); //返回受影响的行数
			//5.查看结果
            if (i>0){
                System.out.println("修改成功");
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            JDBCUtils.closeAll(null,statement,connection);
        }


    }

    @Test
    public void query() {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();

            //3.编写Sql语句
            String sql = "select * from users";
            //4.执行sql语句
            resultSet = statement.executeQuery(sql);
			//5.查看结果
            while (resultSet.next()){
                System.out.println(resultSet.getInt("id"));
                System.out.println(resultSet.getString("name"));
                System.out.println(resultSet.getString("password"));
                System.out.println(resultSet.getString("email"));
                System.out.println(resultSet.getDate("birthday"));
            }



        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            JDBCUtils.closeAll(resultSet,statement,connection);
        }

    }

}


http://www.niftyadmin.cn/n/1779862.html

相关文章

mongodb在secondary不能直接获取primary的信息解决方法

如果通过shell访问mongo,要在secondary进行查询。会出现如下错误: [rootmongodb-secondary2 ~]# mongo MongoDB shell version: 3.0.9 connecting to: test abc:SECONDARY> show dbs 2016-02-20T02:13:18.5270800 E QUERY Error: …

赛门铁克SF如何在线扩容卷组

1、查看磁盘模式:vxdctl -c mode2、所有dg列表信息:-确认服务器上的dg信息,有些是隐藏的,如仲裁盘。vxdisk -o alldgs list 3、SF扫盘:vxdisk scandisks之前的存储配置磁盘步骤省略,但说明,SF只…

JDBC学习(三)---SQL注入问题/PreparedStatement对象

JDBC学习(三)—SQL注入问题/PreparedStatement对象 01 SQL注入问题 所谓SQL注入,就是通过把SQL命令插入到Web表单提交,最终达到欺骗服务器执行恶意的SQL命令。 程序示例:以SQL语句:select * from users where name ‘不存在的…

我的Java开发学习之旅------Workspace in use or cannot be created, choose a different one.--错误解决办法...

今天使用Eclipse时,突然卡死了,然后我强制关闭了Eclipse,再重新打开的时候就报错了,错误如下: Workspace in use or cannot be created, choose a different one. 错误原因:出现这种情况一般是workspace的…

阅读收藏夹

为什么80%的码农都做不了架构师?>>> 腾讯产品经理:BAT面试的时候喜欢怎样的新人(有好书) http://www.woshipm.com/pmd/284339.html 程序日志 http://macrochen.iteye.com/blog/1399082 转载于:https://my.oschina.net/body/blog/620134

MySQL学习(五)---MySQL备份数据库/三大范式

MySQL学习(五)—MySQL备份/数据库三大范式 01 MySQL备份 数据库备份的必要性:1.保证重要数据不丢失 2.数据转移MySQL数据库备份方法:1.mysqldump备份工具 2.数据库管理工具,如SQLyog 3.直接拷贝数据库文件和相关配置文件 mysqldump客户端的…

mysql-bin引起mysql不能启动

日志提示无法找到mysql-bin.000005这个文件 原因是我把其删除了,而在mysql-bin.index文件中却还有mysql-bin.000005的记录,因此启动失败了 解决: cd /var/lib/mysql vi mysql-bin.index 把有记录,但找不到文件的记录删除&#xf…

hdoj 1226 超级password 【隐图BFS】

称号:hdoj 1226 超级password 分析:这题属于隐式图搜索,状态不是非常明显,须要自己建立。 事实上搜索说白了就是暴力。 这个题目就是,首先对给出的能够组成的全部的数依次枚举。长度从小到大。 比方第一组例子&#x…