本篇博客就对Jdbctemplate的使用做一个简单的介绍,以下连接就是Jdbctemplate 所需的jar包,一共是5个
链接:https://pan.baidu.com/s/1RWQXPMk164zJ3mlcejJpHA 提取码:j5pi 1、将下载的5个Jar包导入到项目中

2、编写代码所需的工具类JDBCUtils
package com.Utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 以下链接Druid的工具类
*/
public class JDBCUtil {
//创建Datasource对象
private static DataSource ds;
static {
//创建Properties对象
Properties pro = new Properties();
try {
pro.load(JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
ds=DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 返回链接对象
*/
public static Connection getconnection() throws SQLException {
return ds.getConnection();
}
/**
* 关闭流
*/
public static void close(Statement sta,Connection con){
if(sta != null){
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con !=null){
try {
con.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭三个流
*/
public static void close(ResultSet rs,Statement sta,Connection con){
if(rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(sta !=null){
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con !=null){
try {
con.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取数据源
*/
public static DataSource getDatasource(){
return ds;
}
}
3、编写JDBCTemplate基本程序
package com.Jdbctemplate;
import com.Utils.JDBCUtil;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* 以下程序是使用Jdbctemplate初级方法
*/
public class test {
public static void main(String[] args) {
//1、导入5个Jar包
//2、新建对象
JdbcTemplate jdbc = new JdbcTemplate(JDBCUtil.getDatasource());
//3、编写sql语句
String sql = "update student set age = 20 where name=?";
//4、执行修改语句
int count = jdbc.update(sql, "大王");
//5、打印输出
System.out.println(count);
}
}
4、运行程序,数字1代表成功

希望能给大家带去一些帮助! |