package cn.hu1.com;
import JDBCUtils.JDBCUtils;
import org.springframework.jdbc.core.JdbcTemplate;

public class DemoTemplate {
public static void main(String[] args) {
// 1 导包
// 2 创建JDBCTemplate 对象 依赖于DataSource
JdbcTemplate jt = new JdbcTemplate(JDBCUtils.getDs());
// 3 调用JdbcTemplate方法 CRUD
//String sql = "insert into emppme values(7,?,?)";
String sql = "update emppme set gender = 0 where uname = ?";
int i = jt.update(sql, "孙悟空");
System.out.println(i);
}
}
package JDBCUtils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
* Druid连接池工具类
* */
public class JDBCUtils {
// 1 定义成员变量
private static DataSource ds;
static {
try {
// 2 加载配置文件 获得连接池
Properties pp = new Properties();
pp.load(JDBCUtils.class.getClassLoader().getResourceAsStream("Druid.properties"));
ds = DruidDataSourceFactory.createDataSource(pp);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获得连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(Statement sm, Connection conn) {
if (sm != null) {
try {
sm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//释放资源
public static void close(ResultSet rs, Statement sm, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (sm != null) {
try {
sm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static DataSource getDs(){
return ds;
}
}
 
 
posted on 2019-04-04 08:28  惯她心  阅读(77)  评论(0编辑  收藏  举报