返回ID的核心代码
关键在于PreparedStatement ps = DBConnection.getConn().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)的Statement.RETURN_GENERATED_KEYS
以及通过以下代码取id
ResultSet rs = ps.getGeneratedKeys();
if (rs.next())
return rs.getInt(1);
返回ID的完整代码
//万能修改方法,返回自动增长的ID
public static int executeUpdateReturnId(String sql, Object... args){
try(PreparedStatement ps = DBConnection.getConn().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next())
return rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
连接数据库代码
public class DBConnection {
private static Connection conn;
static {
try {
Properties properties = new Properties();
String propertiesPath = "/Volumes/TOSHIBA EXT/Laner/JavaDT/classExerciseWeb1/webProject/web/WEB-INF/classes/com/laner/myPro.properties";
//Web项目在Tomcat下查找properties文件
// String propertiesPath = Objects.requireNonNull(DBConnection.class.getClassLoader().getResource("myPro.properties")).getPath().replace("%20"," ");
//Java项目查找properties文件
String propertiesPath = "src/com/laner/myPro.properties";
properties.load(new FileInputStream(propertiesPath));
String dbClassName = (String)properties.get("DBClassName");
String dbUrl = (String)properties.get("DBURL");
String dbUsername = (String)properties.get("DBUsername");
String dbPassword = (String)properties.get("DBPassword");
Class.forName(dbClassName);
conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
} catch (IOException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static Connection getConn() {
return conn;
}
}
myPro.properties
DBClassName = com.mysql.cj.jdbc.Driver
DBURL = jdbc:mysql://localhost:3306/jave2105ProjectOne
DBUsername = root
DBPassword = root
总结
更多数据库封装工具可以看这个链接
Java利用反射封装DBUtil,mysql万能增删改查工具类,附源码