package org;
import java.io.FileReader;
import java.io.IOException;
import java.util.;
import java.sql.;
public class practice {
private static final Properties properties = new Properties();
private static final String PATH = “config/properties”;
static {
try {
properties.load(new FileReader(PATH));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
//获取数据源连接对象
private static Connection con() throws SQLException {
return DriverManager.getConnection(
properties.getProperty("mysql.url"),
properties.getProperty("mysql.username"),
properties.getProperty("mysql.password")
);
}
//根据连接对象, SQL命令和预编译参数获取执行对象
private static PreparedStatement pst(Connection con, String sql, Object... args) throws SQLException {
PreparedStatement pst = con.prepareStatement(sql);
if (null != args && args.length > 0) {
for (int i = 0; i < args.length; i++) {
pst.setObject(i + 1, args[i]);
}
}
return pst;
}
//释放
protected static void close(AutoCloseable... closes) {
for (AutoCloseable close : closes) {
if (null != close) {
try {
close.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//执行增删改操作 考点-1
public static int exeUpdate(String sql, Object... args) {
Connection con = null;
PreparedStatement pst = null;
try {
con = con();
pst = pst(con, sql, args);
return pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pst, con);
}
return -1;
}
//批量插入
public static int addBatch(String sql, int colSize, int batchSize, Object... args) {
Connection con = null;
PreparedStatement pst = null;
int affectedRows = 0;
try {
con = con();
pst = pst(con, sql, args);
for (int i = 0, realSize = 0; i < args.length; i += colSize) {
for (int j = i, size = 0; size < colSize; j++, size++) {
pst.setObject(size + 1, args[j]);
}
pst.addBatch();
if (++realSize % batchSize == 0) {
affectedRows += pst.executeBatch().length;
pst.clearBatch();
}
}
affectedRows += pst.executeBatch().length;
pst.clearBatch();
return affectedRows;
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pst, con);
}
return -1;
}
//执行【多列映射实体对象】查询操作 考点-3
public static void exeQuery(String sql, Object... args) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
try {
con = con();
pst = pst(con, sql, args);
rst = pst.executeQuery();
int colSize = rst.getMetaData().getColumnCount();
while (rst.next()) {
for (int i = 1; i <= colSize; i++) {
System.out.print(rst.getObject(i).toString());
System.out.print("\t");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(rst, pst, con);
}
}
public static void main(String[] args) {
final String SQL = "select * from employee";
exeQuery(SQL);
}
}
mysql.username=root
mysql.password=****
mysql.driver = com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost/emps?useSSL=true&&useUnicode=true&&characterEncoding=utf8