//JDBCUtils.getDataSource() 是返回数据库的链接对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
public void add(User user) {
//1.定义sql
String strSql = "insert into user values(null,?,?,?,?,?,?,null,null)";
//2.执行sql
// int update = template.update(strSql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
// System.out.println(update);
try {
java.sql.Connection con = template.getDataSource().getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
KeyHolder key = new GeneratedKeyHolder();
PreparedStatementCreator psc1=new PreparedStatementCreator(){
@Override
public PreparedStatement createPreparedStatement(java.sql.Connection con) throws SQLException {
int i = 0;
//PreparedStatement ps = con.prepareStatement(strSql);
PreparedStatement ps = con.prepareStatement(strSql,PreparedStatement.RETURN_GENERATED_KEYS);
ps.setString(++i, user.getName());
ps.setString(++i, user.getGender() );
ps.setInt(++i,user.getAge() );
ps.setString(++i, user.getAddress() );
ps.setString(++i,user.getQq());
ps.setString(++i,user.getEmail() );
return ps;
}
};
//这里是使用兰步德表达式 上面的是不使用的
// PreparedStatementCreator psc = con -> {
// int i=0;
// PreparedStatement ps = con.prepareStatement(strSql,PreparedStatement.RETURN_GENERATED_KEYS);
// ps.setString(++i, user.getName());
// ps.setString(++i, user.getGender() );
// ps.setInt(++i,user.getAge() );
// ps.setString(++i, user.getAddress() );
// ps.setString(++i,user.getQq());
// ps.setString(++i,user.getEmail() );
// return ps;
// };
template.update(psc1,key);
int cf_id = key.getKey().intValue();
System.out.println(cf_id);
}
下面是JDBCUtils ///
package cn.itcast.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* JDBC工具类 使用Durid连接池
*/
public class JDBCUtils {
private static DataSource ds ;
static {
try {
//1.加载配置文件
Properties pro = new Properties();
//使用ClassLoader加载配置文件,获取字节输入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//2.初始化连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接池对象
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 获取连接Connection对象
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}