通过JDBC访问MySQL几种方法比较

一、使用JDBC最基础方法访问数据库

通过JDBC操作数据库时需要导入包mysql-connector.jar

public class Base{
	public static void main(String[] args){
		class.ForName("com.mysql.cj.jdbc.Driver");//5.0后可以省略
    	Connection conn = DriverManger.getConnection("jdbc:mysql://localhost:3306/Su?serverTimezone = UTC");
		Statement sta = conn.createStatement();
		ResultSet result = sta.executeQuery(sql);//执行
		while(result.next){
			System.out.println("查询到 "+resultSet.getString("name"));
		}
		conn.close();
		sta.closse();
		result.close();
	}
}

二、使用一个自定义的工具类简化获取连接和释放资源过程

public class JDBC_Utils{
	String uel,user,password;
	static{
		Properties prop = new Properties();
		//此处需要用try来处理异常
		ClassLoader cl = JDBC_Utils.class.getClassLoader();
		URL res = cl.getResource("jdbc.properties");//自定义一个配置文件,放入src下
		prop.load(new FileReader(res.getPath));//获取文件路径后载入
		url=prop.getProperty("url");//在配置文件中对应信息,url为key,其值为value
		url = pro.getProperty("url");
        user = pro.getProperty("user");
        password = pro.getProperty("password");
        driver = pro.getProperty("driver");
        Class.forName(driver);
	}
	public static Connection getConnection(){
		Connection conn = null;
		conn = DriverManager.getConnection(url,user,password);//此处需要用try
		return conn;
	}
	public static void Close(Statement sta, Connection conn, ResultSet res){
	if(res != null){
        try {
            sta.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(sta != null){
        try {
            sta.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(conn != null){
        try {
            sta.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    }
	}
}

在连接过程中,使用这个工具类

public class UseJDBC_Utils{
	public static void main(String[] args) {
	Connection conn = JDBC_Utils.getConnection;//此步骤自动调用JDBC_Utils读取配置文件
	//-----后续代码
	JDBC_Utils.close();
	}
}

三、使用数据库连接池来解决频繁申请数据库访问

数据库连接池技术中两类支持:c3p0和druid
由于c3p0技术比较老旧,不再记录。
使用druid之前需要先导入druid.jar,在src下放入druid.properties文件,文件内容如下:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/su?serverTimezone=UTC
username=root
password=123456

#初始化链接数量
initialSize=5

#最大连接数
maxActive=10

#最大超时时间ms
maxWait=3000
minIdle=3

其中的maxIdle已经被弃用,故删除。否则在运行时会提示错误,但不影响运行结果。

public class Druid_JDBC{
	public static void main(String[] args) {
		Properties prop = new Properties();
		InputStream res = Druid_JDBC.class.getClassLoader().getResourceAsStream("druid.properties");//直接获取流,可以省去中间转换步骤
		prop.load(res);
		DataSource ds = DruidDataSourceFactory.createDataSource(prop);//此处需要依靠工厂类来完成连接池对象的获取
		Connection conn = ds.getConnection();//不再依靠工具类也可以从配置文件获取连接了,而且此时再close不再是关闭连接而是把连接对象收回连接池。
		Statement sta = conn.CreateStatement();
		//···后续代码
	}
}

与二的区别在于,不再需要自己配置工具类,可以通过druid的包和properties文件直接获取连接,且连接池可以提供大量用户访问。

四、给druid连接池设置一个工具类简化获取连接

    public class DruidJDBCUtils {
        //定义成员变量
        private static DataSource ds = null;
        static {
            //加载配置文件
            Properties prop = new Properties();
            try {
                prop.load(DruidJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
                //2.获取DataSource
                ds = DruidDataSourceFactory.createDataSource(prop);
    
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
    
            }
        }
        //获取连接
        public static Connection getConnection(){
            Connection conn = null;
            try {
                conn = ds.getConnection();//此处无需参数,因为url、账户等会根据配置文件读取
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return conn;
    
        }
        public static void close(Statement statement,Connection connection){
    
            try {
                if (statement != null)
                    statement.close();//不为空关闭
                if(connection != null)
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(Statement statement, Connection connection, ResultSet resultSet){
        close(statement,connection);
        try {
            if(resultSet != null)
                resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource(){//返回数据池
        return ds;
    }

}

使用druid的工具类访问数据库

public class DruidJDBCpra {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement stat = null,stat2 = null;
        ResultSet res = null;
        String sql = "insert into Bills (name,acount) values (?,?)";
        String sqlBase = "select * from Bills";
        Person person;

        try {//获取连接
            conn = DruidJDBCUtils.getConnection();
            //对象初始化,插入值
            stat = conn.prepareStatement(sql);
            stat.setString(1,"张");
            stat.setString(2,"2000");
            //对象初始化,读取值
            stat2 = conn.prepareStatement(sqlBase);
            //对象执行
            stat.executeUpdate();
            res = stat2.executeQuery();

            List<Person> list = new ArrayList<>();
            while (res.next()){
                person = new Person();
                //获取值
                person.setName(res.getString("name"));
                person.setAcount(res.getDouble("acount"));
                //放入集合
                list.add(person);
            }
            for (Person person1 : list) {
                System.out.println(person1.getName()+"   "+person1.getAcount());
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidJDBCUtils.close(stat,conn,res);
        }
    }
}
class Person{
    private String name;
    private double acount;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getAcount() {
        return acount;
    }
    public void setAcount(double acount) {
        this.acount = acount;
    }
}

三提供了连接池提高了数据库访问效率,并且采用加载druid.properties文件的方式来加载数据库信息等,但仍需要借助Druid的工厂类、Properties集合以及DataSource来获取连接。
因此,四定义了在druid基础上的工具类,在访问数据库时可以通过这个工具类方法getConnection直接获取连接以及通过Close方法回收连接。
并且四的工具类中,增加了一个返回数据源的方法,以供使用Spring时调用。

五、Spring Template

使用方法:
1.导入包(jdbc_template,包括commons-loging在内共五个)
2.JdbcTemplate可以直接使用new的方式,参数为数据源,可由刚刚的工具类方法提供。

public class SpringJDBC {
    public static void main(String[] args) {
        JdbcTemplate jtl = new JdbcTemplate(DruidJDBCUtils.getDataSource());//获取线程池
        String sql = "update Bills set acount = 1000 where id = ?";
        jtl.update(sql,1);//无需申请链接和释放资源,框架完成了。参数为占位符的值
    }
}

此举仅通过一行代码即可解决连接问题,并且JDBCTemplate对象只需要执行sql语句即可,获取PreparedStatement、结束后归还连接等问题框架内已经解决。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值