昨天博客忘记发了,补一下。
昨天上课王老师强调了智能排产。昨天在做一个可以实现不同表都可以调用的增函数。
public static void insertData(String tableName, String... columnValuePairs) {标签:总结,String,11.16,StringBuilder,每日,columnValuePairs,length,columns,append From: https://www.cnblogs.com/ZRGUGUGU818/p/17839629.html
Connection connection = getConnection();
try {
// 执行数据库操作
// 例如,执行SQL查询或插入数据
// 确保列和值的数量匹配
if (columnValuePairs.length % 2 != 0) {
throw new IllegalArgumentException("列值对必须是偶数");
}
StringBuilder columns = new StringBuilder();
StringBuilder values = new StringBuilder();
for (int i = 0; i < columnValuePairs.length; i += 2) {
columns.append(columnValuePairs[i]);
values.append("?");
if (i < columnValuePairs.length - 2) {
columns.append(", ");
values.append(", ");
}
}
String sql = String.format("INSERT INTO %s (%s) VALUES (%s)", tableName, columns, values);
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
for (int i = 0; i < columnValuePairs.length; i += 2) {
preparedStatement.setString(i / 2 + 1, columnValuePairs[i + 1]);
}
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
}
// 最后,关闭数据库连接
close(connection);
}