JDBC的连接

此文章仅作为我学习阶段的一个参考

最原始的JDBC

这里面的代码是极其不方便的,如果再去调用一次此代码就有一些加载和连接类的代码需要重复去写,所以下面会给出提取的工具类

   package com.li.jdbc;

import java.sql.*;

//第一个JDBC代码
public class jdbcFirst {

    public static void main(String[] args) throws SQLException {
        //加载驱动类
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //创建getConnection参数
        String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username = "root";     //
        String password = "123456";
        //连接成功,数据库对象
        Connection connection = DriverManager.getConnection(url, username, password);

        //执行sql 的对象  statement 执行sql 的对象
        Statement statement = connection.createStatement();

        //执行的结果集
        String sql = "SELECT * FROM student";   //编写sql

        ResultSet resultSet = statement.executeQuery(sql);  //返回的结果集 --->封装了所有的查询结果...

        //   ResultSet resultSet1 = statement.executeUpdate("");   // 更新,插入,删除;
        //   boolean execute = statement.execute();    //可以执行任何sql 但效率低

        // statement.executeBatch();   可以放入多个sql

        while (resultSet.next()) {
            System.out.println("studentname:" + resultSet.getObject("studentname"));
            System.out.println("address:" + resultSet.getObject("address"));
            System.out.println("");

             //   resultSet.getObject()   //在不知道列类型的时候用
            //  resultSet.getString    //指定的数据类型
        }

        //释放连接    //释放资源是必不可少的  因为会占用内存
        resultSet.close();
        statement.close();
        connection.close();
    }
}

JDBC的工具类

这里这个工具的好处就是,如果需要去连接其他的更改用户可以直接更改properties 文件里面的相关内容(下面给出调试的properties文件)

我的properties文件(注意键的名称一定要和下面的这个一至)
driverClassName=com.mysql.jdbc.Driver   //
url = jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true
username = root
password = 123456
我的JDBCUtil 类
package com.li.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil2 {
    private static String url;
    private static String driver;
    private static String userName;
    private static String pwd;

    static {
        try {

            //加载文件变为输入流
            InputStream inputStream = JDBCUtil2.class.getClassLoader().getResourceAsStream("db.properties");
            
            //创建Properties对象
            Properties properties = new Properties();
            
            //将输入流加载入Properties对象内
            properties.load(inputStream);
			
			//将properties中的内容转换为字符串
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            userName = properties.getProperty("username");
            pwd = properties.getProperty("password");

            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static Connection connection = null;
   
   //获取Connection的方法
    public static Connection getConnection() {
        if (connection == null) {
            try {
                connection = DriverManager.getConnection(url, userName, pwd);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return connection;
    }
		
		// 关闭资源的方法  用于关闭 Connection(连接资源), PreparedStatement(SQL语句资源), ResultSet (结果集)
    public static void relese(Connection conn, PreparedStatement pr, ResultSet rs) {
        try {
            if (conn != null)
                conn.close();
            if (pr != null)
                pr.close();
            if (rs != null)
                rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Test_JDBCUtil 类
package com.li.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestJDBCUtil2_PreparedStatement {

    private static Connection connection;
    private static PreparedStatement preparedStatement;

    public static void main(String[] args) {
        try {
            //创建连接
            connection = JDBCUtil2.getConnection();
            //创建语句
            String sql = "select * from student where `sex` = ?";   //PreparedStatemnt的sql可以用占位符(?)
            //创建Statement
            preparedStatement = connection.prepareStatement(sql);
     		//根据自己的需求,填充占位符  前一个参数是代表第几个占位符  第二个参数是填充的Value.
            preparedStatement.setString(1, "1");


            // 执行sql
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                System.out.println(resultSet.getString("studentname"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        
        JDBCUtil2.relese(connection, preparedStatement, resultSet);

    }
}

池化技术

池化技术可以改善代码的效率 今天要写的就是DBCP的池化技术的工具类
在工程中加入 commons-dbcp-1.2.2.jar commons-pool-1.3.jar两个依赖

package com.li.jdbc;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil_DBCP {

    static {
        try {
            InputStream inputStream = JDBCUtil_DBCP.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(inputStream);

            //创建数据源,工厂模式  ---->创建
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {

        }
    }

    private static DataSource dataSource;


    public static Connection getConn() throws SQLException {
    //从数据源的对象中获取连接
        return dataSource.getConnection();
    }

    public static void release(Connection connection, PreparedStatement preparedStatement, ResultSet rs) {

        try {
            if (connection != null)
                connection.close();

            if (preparedStatement != null)
                preparedStatement.close();

            if (rs != null)
                rs.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值