1
mirror of https://github.com/CarmJos/EasySQL.git synced 2026-06-05 09:01:26 +08:00

Compare commits

...

20 Commits

Author SHA1 Message Date
carm 72259bef81 [0.3.3] 版本更新
- `[F]` 修复上个版本中 QueryAction 的 executeFunction 方法未重写 SQLAction 中同方法导致的链接未被自动关闭的问题。
- `[U]` 更新软件依赖于Maven相关插件的版本。
2022-01-29 04:57:29 +08:00
carm 8924258635 [0.3.3] 版本更新
- `[F]` 修复上个版本中 QueryAction 的 executeFunction 方法未重写 SQLAction 中同方法导致的链接未被自动关闭的问题。
- `[U]` 更新软件依赖于Maven相关插件的版本。
2022-01-29 04:49:30 +08:00
carm 6322689d39 Merge pull request #8 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-release-plugin-2.5.3
Bump maven-release-plugin from 2.5.1 to 2.5.3
2022-01-29 03:51:56 +08:00
carm 90fb21b72c Merge pull request #5 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-javadoc-plugin-3.3.1
Bump maven-javadoc-plugin from 3.2.0 to 3.3.1
2022-01-29 03:51:44 +08:00
dependabot[bot] 47e588dd19 Bump maven-release-plugin from 2.5.1 to 2.5.3
Bumps maven-release-plugin from 2.5.1 to 2.5.3.

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-release-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-28 19:51:28 +00:00
carm c91375f438 Merge pull request #4 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-jar-plugin-3.2.2
Bump maven-jar-plugin from 3.2.0 to 3.2.2
2022-01-29 03:51:26 +08:00
carm b2d2626b31 Merge pull request #6 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-compiler-plugin-3.9.0
Bump maven-compiler-plugin from 3.8.1 to 3.9.0
2022-01-29 03:51:21 +08:00
carm 139c1d743e Merge pull request #7 from CarmJos/dependabot/maven/com.github.chris2018998-beecp-3.3.1
Bump beecp from 3.3.0 to 3.3.1
2022-01-29 03:51:10 +08:00
dependabot[bot] 2aa52c9d7b Bump beecp from 3.3.0 to 3.3.1
Bumps [beecp](https://github.com/Chris2018998/BeeCP) from 3.3.0 to 3.3.1.
- [Release notes](https://github.com/Chris2018998/BeeCP/releases)
- [Commits](https://github.com/Chris2018998/BeeCP/compare/3.3.0...3.3.1)

---
updated-dependencies:
- dependency-name: com.github.chris2018998:beecp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-28 19:50:27 +00:00
dependabot[bot] ebd1e54a8c Bump maven-compiler-plugin from 3.8.1 to 3.9.0
Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.8.1 to 3.9.0.
- [Release notes](https://github.com/apache/maven-compiler-plugin/releases)
- [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.8.1...maven-compiler-plugin-3.9.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-compiler-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-28 19:49:47 +00:00
dependabot[bot] 9ba7afffc3 Bump maven-javadoc-plugin from 3.2.0 to 3.3.1
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.2.0 to 3.3.1.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.2.0...maven-javadoc-plugin-3.3.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-28 19:49:33 +00:00
dependabot[bot] c4bbbd132e Bump maven-jar-plugin from 3.2.0 to 3.2.2
Bumps [maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.2.0 to 3.2.2.
- [Release notes](https://github.com/apache/maven-jar-plugin/releases)
- [Commits](https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.2.0...maven-jar-plugin-3.2.2)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-jar-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-28 19:49:07 +00:00
carm 8652d4b824 Create dependabot.yml 2022-01-29 03:48:12 +08:00
carm e8f9b5532e 修改项目名 2022-01-29 03:28:50 +08:00
carm 3dd7702a26 删除名字中用于排序的数字 2022-01-29 03:28:22 +08:00
carm f5d04bb0bb [v0.3.2] 版本更新
- [A] 对于UPDATE类型的SQL操作采用 try-with-resources 形式获取链接与statement,避免中途报错而导致相关流未关闭。
- [U] 声明 setKeyIndex(int) 过时并移除 defaultKeyIndex() 方法,改为更明确的 setReturnGeneratedKeys(boolean) 与 returnGeneratedKeys() 方法,避免填入错误的index。
2022-01-29 03:01:10 +08:00
carm 7d11131b97 [v0.3.1] 修复一些小的规范问题 2022-01-26 22:20:53 +08:00
carm 0850194e82 [v0.3.1] 修复一些小的规范问题 2022-01-26 15:01:30 +08:00
carm ba4731c331 [v0.3.1] 修复一些小的规范问题 2022-01-26 15:00:05 +08:00
carm 36a23af450 [v0.3.1] 修复一些小的规范问题 2022-01-26 14:49:19 +08:00
33 changed files with 531 additions and 320 deletions
+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "maven" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "daily"
+2 -2
View File
@@ -5,7 +5,7 @@
<parent>
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId>
<version>0.3.1</version>
<version>0.3.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -19,7 +19,7 @@
<artifactId>easysql-api</artifactId>
<packaging>jar</packaging>
<name>00-EasySQL-API</name>
<name>EasySQL-API</name>
<description>EasySQL的接口部分。用于打包到公共项目的API中,避免项目过大。</description>
<url>https://github.com/CarmJos/EasySQL</url>
@@ -98,7 +98,7 @@ public interface SQLAction<T> {
*/
@Nullable
default <R> R execute(@NotNull SQLFunction<T, R> function,
@Nullable SQLExceptionHandler exceptionHandler) {
@Nullable SQLExceptionHandler exceptionHandler) {
return execute(function, null, exceptionHandler);
}
@@ -114,8 +114,8 @@ public interface SQLAction<T> {
@Nullable
@Contract("_,!null,_ -> !null")
default <R> R execute(@NotNull SQLFunction<T, R> function,
@Nullable R defaultResult,
@Nullable SQLExceptionHandler exceptionHandler) {
@Nullable R defaultResult,
@Nullable SQLExceptionHandler exceptionHandler) {
try {
return executeFunction(function, defaultResult);
} catch (SQLException exception) {
@@ -133,7 +133,7 @@ public interface SQLAction<T> {
* @throws SQLException 当SQL操作出现问题时抛出
*/
@Nullable
default <R> R executeFunction(@NotNull SQLFunction<T, R> function) throws SQLException {
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function) throws SQLException {
return executeFunction(function, null);
}
@@ -148,11 +148,10 @@ public interface SQLAction<T> {
*/
@Nullable
@Contract("_,!null -> !null")
default <R> R executeFunction(@NotNull SQLFunction<T, R> function,
@Nullable R defaultResult) throws SQLException {
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function,
@Nullable R defaultResult) throws SQLException {
try {
T value = execute();
R result = function.apply(value);
R result = function.apply(execute());
return result == null ? defaultResult : result;
} catch (SQLException exception) {
throw new SQLException(exception);
@@ -182,7 +181,7 @@ public interface SQLAction<T> {
* @param failure 异常处理器 默认为 {@link SQLAction#defaultExceptionHandler()}
*/
void executeAsync(@Nullable SQLHandler<T> success,
@Nullable SQLExceptionHandler failure);
@Nullable SQLExceptionHandler failure);
default void handleException(@Nullable SQLExceptionHandler handler, SQLException exception) {
if (handler == null) handler = defaultExceptionHandler();
@@ -6,39 +6,50 @@ import java.util.List;
public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
/**
* 设定多组SQL语句中所有 ? 对应的参数
*
* @param allParams 所有参数内容
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams);
/**
* 设定多组SQL语句中所有 ? 对应的参数
*
* @param allParams 所有参数内容
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams);
/**
* 添加一组SQL语句中所有 ? 对应的参数
*
* @param params 参数内容
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction addParamsBatch(Object... params);
/**
* 添加一组SQL语句中所有 ? 对应的参数
*
* @param params 参数内容
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction addParamsBatch(Object... params);
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex);
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link PreparedSQLUpdateBatchAction}
* @see #setReturnGeneratedKeys(boolean)
*/
@Deprecated
default PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex) {
return setReturnGeneratedKeys(keyColumnIndex > 0);
}
/**
* 默认主键序列的数值为 -1 (≤0) ,即默认返回发生变更的行数
*
* @return 默认主键序列
*/
default PreparedSQLUpdateBatchAction defaultKeyIndex() {
return setKeyIndex(-1); // will return changed lines number
}
/**
* 设定该操作返回自增键序列
*
* @return {@link PreparedSQLUpdateBatchAction}
*/
default PreparedSQLUpdateBatchAction returnGeneratedKeys() {
return setReturnGeneratedKeys(true);
}
/**
* 设定该操作是否返回自增键序列。
*
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey);
}
@@ -4,24 +4,34 @@ import cc.carm.lib.easysql.api.SQLAction;
public interface SQLUpdateAction extends SQLAction<Integer> {
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link SQLUpdateAction}
*/
SQLUpdateAction setKeyIndex(int keyColumnIndex);
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link SQLUpdateAction}
* @see #setReturnGeneratedKey(boolean)
*/
@Deprecated
default SQLUpdateAction setKeyIndex(int keyColumnIndex) {
return setReturnGeneratedKey(keyColumnIndex > 0);
}
/**
* 默认主键序列的数值为 -1 (≤0) ,即默认返回发生变更的行数
*
* @return 默认主键序列
*/
default SQLUpdateAction defaultKeyIndex() {
return setKeyIndex(-1); // will return changed lines number
}
/**
* 设定该操作返回自增键序列
*
* @return {@link SQLUpdateAction}
*/
default SQLUpdateAction returnGeneratedKey() {
return setReturnGeneratedKey(true);
}
/**
* 设定该操作是否返回自增键序列。
*
* @return {@link SQLUpdateAction}
*/
SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey);
}
@@ -15,6 +15,7 @@ public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
*/
SQLUpdateBatchAction addBatch(@NotNull String sql);
@Override
default @NotNull String getSQLContent() {
return getSQLContents().get(0);
}
@@ -32,20 +32,10 @@ import java.sql.SQLException;
*/
public interface QueryAction extends SQLAction<SQLQuery> {
/**
* 执行语句并处理返回值
*
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
* @param function 处理方法
* @param <R> 需要返回的内容
* @return 指定类型数据
* @throws SQLException 当SQL操作出现问题时抛出
*/
@Nullable
@Contract("!null, _ -> !null")
default <R> R executeFunction(@Nullable R defaultResult,
@NotNull SQLFunction<SQLQuery, R> function) throws SQLException {
@Override
@Contract("_,!null -> !null")
default <R> @Nullable R executeFunction(@NotNull SQLFunction<@NotNull SQLQuery, R> function,
@Nullable R defaultResult) throws SQLException {
try (SQLQuery value = execute()) {
R result = function.apply(value);
return result == null ? defaultResult : result;
@@ -28,7 +28,7 @@ public enum ForeignKeyRule {
*/
CASCADE("CASCADE");
String ruleName;
final String ruleName;
ForeignKeyRule(String ruleName) {
this.ruleName = ruleName;
@@ -29,7 +29,7 @@ public enum IndexType {
FULLTEXT_INDEX("FULLTEXT");
String name;
final String name;
IndexType(String name) {
this.name = name;
+2 -2
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.1</version>
<version>0.3.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -19,7 +19,7 @@
<artifactId>easysql-impl</artifactId>
<packaging>jar</packaging>
<name>01-EasySQL-Impl</name>
<name>EasySQL-Impl</name>
<description>EasySQL的实现部分。</description>
<url>https://github.com/CarmJos/EasySQL</url>
@@ -15,63 +15,60 @@ import java.util.List;
import java.util.stream.Collectors;
public class PreparedSQLBatchUpdateActionImpl
extends AbstractSQLAction<List<Integer>>
implements PreparedSQLUpdateBatchAction {
extends AbstractSQLAction<List<Integer>>
implements PreparedSQLUpdateBatchAction {
int keyIndex = -1;
List<Object[]> allParams;
boolean returnKeys = false;
List<Object[]> allParams;
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
super(manager, sql);
this.allParams = new ArrayList<>();
}
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
super(manager, sql);
this.allParams = new ArrayList<>();
}
@Override
public PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams) {
List<Object[]> paramsList = new ArrayList<>();
allParams.forEach(paramsList::add);
this.allParams = paramsList;
return this;
}
@Override
public PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams) {
List<Object[]> paramsList = new ArrayList<>();
allParams.forEach(paramsList::add);
this.allParams = paramsList;
return this;
}
@Override
public PreparedSQLUpdateBatchAction addParamsBatch(Object[] params) {
this.allParams.add(params);
return this;
}
@Override
public PreparedSQLUpdateBatchAction addParamsBatch(Object... params) {
this.allParams.add(params);
return this;
}
@Override
public PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex) {
this.keyIndex = keyColumnIndex;
return this;
}
@Override
public PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey) {
this.returnKeys = returnGeneratedKey;
return this;
}
@Override
public @NotNull List<Integer> execute() throws SQLException {
List<Integer> returnedValues;
Connection connection = getManager().getConnection();
PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
connection, getSQLContent(), allParams, keyIndex > 0
);
outputDebugMessage();
if (keyIndex > 0) {
statement.executeBatch();
List<Integer> generatedKeys = new ArrayList<>();
ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet != null) {
while (resultSet.next()) generatedKeys.add(resultSet.getInt(keyIndex));
resultSet.close();
}
returnedValues = generatedKeys;
} else {
int[] executed = statement.executeBatch();
returnedValues = Arrays.stream(executed).boxed().collect(Collectors.toList());
}
@Override
public @NotNull List<Integer> execute() throws SQLException {
try (Connection connection = getManager().getConnection()) {
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
connection, getSQLContent(), allParams, returnKeys
)) {
statement.close();
connection.close();
outputDebugMessage();
int[] executed = statement.executeBatch();
return returnedValues;
}
if (!returnKeys) return Arrays.stream(executed).boxed().collect(Collectors.toList());
else {
try (ResultSet resultSet = statement.getGeneratedKeys()) {
List<Integer> generatedKeys = new ArrayList<>();
while (resultSet.next()) {
generatedKeys.add(resultSet.getInt(1));
}
return generatedKeys;
}
}
}
}
}
}
@@ -24,18 +24,18 @@ public class PreparedSQLUpdateActionImpl
}
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
@Nullable List<Object> params) {
@Nullable List<Object> params) {
this(manager, sql, params == null ? null : params.toArray());
}
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
@Nullable Object[] params) {
@Nullable Object[] params) {
super(manager, sql);
this.params = params;
}
@Override
public PreparedSQLUpdateActionImpl setParams(Object[] params) {
public PreparedSQLUpdateActionImpl setParams(Object... params) {
this.params = params;
return this;
}
@@ -53,28 +53,25 @@ public class PreparedSQLUpdateActionImpl
@Override
public @NotNull Integer execute() throws SQLException {
int value = -1;
try (Connection connection = getManager().getConnection()) {
try (PreparedStatement statement = StatementUtil.createPrepareStatement(
connection, getSQLContent(), params, returnGeneratedKeys
)) {
outputDebugMessage();
int changes = statement.executeUpdate();
if (!returnGeneratedKeys) return changes;
else {
try (ResultSet resultSet = statement.getGeneratedKeys()) {
return resultSet.next() ? resultSet.getInt(1) : -1;
}
}
Connection connection = getManager().getConnection();
PreparedStatement statement = StatementUtil.createPrepareStatement(
connection, getSQLContent(), params, keyIndex > 0
);
outputDebugMessage();
if (keyIndex > 0) {
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet != null) {
if (resultSet.next()) value = resultSet.getInt(keyIndex);
resultSet.close();
}
} else {
value = statement.executeUpdate();
}
statement.close();
connection.close();
return value;
}
}
@@ -13,42 +13,36 @@ public class SQLUpdateActionImpl
extends AbstractSQLAction<Integer>
implements SQLUpdateAction {
int keyIndex = -1;
boolean returnGeneratedKeys = false;
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
super(manager, sql);
}
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
super(manager, sql);
}
@Override
public @NotNull Integer execute() throws SQLException {
int returnedValue = -1;
Connection connection = getManager().getConnection();
Statement statement = connection.createStatement();
outputDebugMessage();
if (keyIndex > 0) {
statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS);
ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet != null) {
if (resultSet.next()) {
returnedValue = resultSet.getInt(keyIndex);
}
resultSet.close();
}
} else {
returnedValue = statement.executeUpdate(getSQLContent());
}
@Override
public @NotNull Integer execute() throws SQLException {
try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) {
outputDebugMessage();
statement.close();
connection.close();
if (!returnGeneratedKeys) {
return statement.executeUpdate(getSQLContent());
} else {
statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS);
return returnedValue;
}
try (ResultSet resultSet = statement.getGeneratedKeys()) {
return resultSet.next() ? resultSet.getInt(1) : -1;
}
}
}
}
}
@Override
public SQLUpdateActionImpl setKeyIndex(int keyIndex) {
this.keyIndex = keyIndex;
return this;
}
@Override
public SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey) {
this.returnGeneratedKeys = returnGeneratedKey;
return this;
}
}
@@ -36,20 +36,21 @@ public class SQLUpdateBatchActionImpl
@Override
public @NotNull List<Integer> execute() throws SQLException {
Connection connection = getManager().getConnection();
Statement statement = connection.createStatement();
outputDebugMessage();
try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) {
outputDebugMessage();
for (String content : this.sqlContents) {
statement.addBatch(content);
}
int[] executed = statement.executeBatch();
return Arrays.stream(executed).boxed().collect(Collectors.toList());
}
for (String content : this.sqlContents) {
statement.addBatch(content);
}
int[] executed = statement.executeBatch();
List<Integer> returnedValues = Arrays.stream(executed).boxed().collect(Collectors.toList());
statement.close();
connection.close();
return returnedValues;
}
@Override
@@ -9,7 +9,6 @@ import org.jetbrains.annotations.Nullable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@@ -25,7 +24,7 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
}
@Override
public PreparedQueryActionImpl setParams(@Nullable Object[] params) {
public PreparedQueryActionImpl setParams(@Nullable Object... params) {
this.params = params;
return this;
}
@@ -54,21 +53,34 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
Connection connection = getManager().getConnection();
PreparedStatement preparedStatement;
if (handler == null) {
preparedStatement = StatementUtil.createPrepareStatement(connection, getSQLContent(), this.params);
} else {
preparedStatement = connection.prepareStatement(getSQLContent());
handler.accept(preparedStatement);
try {
if (handler == null) {
preparedStatement = StatementUtil.createPrepareStatement(connection, getSQLContent(), this.params);
} else {
preparedStatement = connection.prepareStatement(getSQLContent());
handler.accept(preparedStatement);
}
} catch (SQLException exception) {
connection.close();
throw exception;
}
long executeTime = System.currentTimeMillis();
ResultSet resultSet = preparedStatement.executeQuery();
try {
long executeTime = System.currentTimeMillis();
SQLQueryImpl query = new SQLQueryImpl(
getManager(), this,
connection, preparedStatement,
preparedStatement.executeQuery(),
executeTime
);
getManager().getActiveQuery().put(getActionUUID(), query);
return new SQLQueryImpl(
getManager(), this,
connection, preparedStatement, resultSet,
executeTime
);
return query;
} catch (SQLException exception) {
preparedStatement.close();
connection.close();
throw exception;
}
}
}
@@ -10,7 +10,6 @@ import cc.carm.lib.easysql.query.SQLQueryImpl;
import org.jetbrains.annotations.NotNull;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@@ -24,21 +23,32 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
public @NotNull SQLQueryImpl execute() throws SQLException {
Connection connection = getManager().getConnection();
Statement statement = connection.createStatement();
Statement statement;
try {
statement = connection.createStatement();
} catch (SQLException ex) {
connection.close();
throw ex;
}
outputDebugMessage();
try {
long executeTime = System.currentTimeMillis();
SQLQueryImpl query = new SQLQueryImpl(
getManager(), this,
connection, statement,
statement.executeQuery(getSQLContent()),
executeTime
);
getManager().getActiveQuery().put(getActionUUID(), query);
long executeTime = System.currentTimeMillis();
ResultSet resultSet = statement.executeQuery(getSQLContent());
SQLQueryImpl query = new SQLQueryImpl(
getManager(), this,
connection, statement, resultSet,
executeTime
);
getManager().getActiveQuery().put(getActionUUID(), query);
return query;
return query;
} catch (SQLException exception) {
statement.close();
connection.close();
throw exception;
}
}
@@ -62,7 +62,7 @@ public abstract class AbstractConditionalBuilder<B extends ConditionalBuilder<B,
public B addCondition(
@NotNull String[] queryNames, @Nullable Object[] queryValues
) {
if (queryNames.length != queryValues.length) {
if (queryValues == null || queryNames.length != queryValues.length) {
throw new RuntimeException("queryNames are not match with queryValues");
}
for (int i = 0; i < queryNames.length; i++) {
@@ -111,7 +111,7 @@ public class TableCreateBuilderImpl extends AbstractSQLBuilder implements TableC
}
@Override
public TableCreateBuilder setColumns(@NotNull String[] columns) {
public TableCreateBuilder setColumns(@NotNull String... columns) {
this.columns = Arrays.asList(columns);
return this;
}
@@ -8,80 +8,81 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TableQueryBuilderImpl
extends AbstractConditionalBuilder<TableQueryBuilder, PreparedQueryAction>
implements TableQueryBuilder {
extends AbstractConditionalBuilder<TableQueryBuilder, PreparedQueryAction>
implements TableQueryBuilder {
@NotNull String tableName;
@NotNull String tableName;
String[] columns;
String[] columns;
@Nullable String orderBy;
@Nullable String orderBy;
int[] pageLimit;
int[] pageLimit;
public TableQueryBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
super(manager);
this.tableName = tableName;
}
public TableQueryBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
super(manager);
this.tableName = tableName;
}
@Override
public PreparedQueryActionImpl build() {
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("SELECT").append(" ");
if (columns == null || columns.length < 1) {
sqlBuilder.append("*");
} else {
for (int i = 0; i < columns.length; i++) {
String name = columns[i];
sqlBuilder.append("`").append(name).append("`");
if (i != columns.length - 1) {
sqlBuilder.append(",");
}
}
}
@Override
public PreparedQueryActionImpl build() {
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("SELECT").append(" ");
if (columns == null || columns.length < 1) {
sqlBuilder.append("*");
} else {
for (int i = 0; i < columns.length; i++) {
String name = columns[i];
sqlBuilder.append("`").append(name).append("`");
if (i != columns.length - 1) {
sqlBuilder.append(",");
}
}
}
sqlBuilder.append(" ").append("FROM").append(" ");
sqlBuilder.append("`").append(tableName).append("`");
sqlBuilder.append(" ").append("FROM").append(" ");
sqlBuilder.append("`").append(tableName).append("`");
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
if (pageLimit != null && pageLimit.length == 2) {
sqlBuilder.append(" LIMIT ").append(pageLimit[0]).append(",").append(pageLimit[1]);
} else if (limit > 0) {
sqlBuilder.append(" ").append(buildLimitSQL());
}
if (orderBy != null) sqlBuilder.append(" ").append(orderBy);
if (orderBy != null) sqlBuilder.append(orderBy);
if (pageLimit != null && pageLimit.length == 2) {
sqlBuilder.append(" LIMIT ").append(pageLimit[0]).append(",").append(pageLimit[1]);
} else if (limit > 0) {
sqlBuilder.append(" ").append(buildLimitSQL());
}
return new PreparedQueryActionImpl(getManager(), sqlBuilder.toString())
.setParams(hasConditionParams() ? getConditionParams() : null);
}
@Override
public @NotNull String getTableName() {
return tableName;
}
return new PreparedQueryActionImpl(getManager(), sqlBuilder.toString())
.setParams(hasConditionParams() ? getConditionParams() : null);
}
@Override
public TableQueryBuilderImpl selectColumns(@NotNull String[] columnNames) {
this.columns = columnNames;
return this;
}
@Override
public @NotNull String getTableName() {
return tableName;
}
@Override
public TableQueryBuilder orderBy(@NotNull String columnName, boolean asc) {
this.orderBy = "ORDER BY `" + columnName + "` " + (asc ? "ASC" : "DESC");
return this;
}
@Override
public TableQueryBuilderImpl selectColumns(@NotNull String... columnNames) {
this.columns = columnNames;
return this;
}
@Override
public TableQueryBuilder setPageLimit(int start, int end) {
this.pageLimit = new int[]{start, end};
return this;
}
@Override
public TableQueryBuilder orderBy(@NotNull String columnName, boolean asc) {
this.orderBy = "ORDER BY `" + columnName + "` " + (asc ? "ASC" : "DESC");
return this;
}
@Override
protected TableQueryBuilderImpl getThis() {
return this;
}
@Override
public TableQueryBuilder setPageLimit(int start, int end) {
this.pageLimit = new int[]{start, end};
return this;
}
@Override
protected TableQueryBuilderImpl getThis() {
return this;
}
}
@@ -62,6 +62,7 @@ public class SQLManagerImpl implements SQLManager {
if (isDebugMode()) getLogger().info("[DEBUG] " + msg);
}
@Override
public Logger getLogger() {
return LOGGER;
}
@@ -103,7 +104,7 @@ public class SQLManagerImpl implements SQLManager {
}
@Override
public List<Integer> executeSQLBatch(@NotNull String sql, String[] moreSQL) {
public List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL) {
SQLUpdateBatchAction action = new SQLUpdateBatchActionImpl(this, sql);
if (moreSQL != null && moreSQL.length > 0) {
Arrays.stream(moreSQL).forEach(action::addBatch);
@@ -128,16 +128,12 @@ public class StatementUtil {
* @return 数据类型,默认为 {@link Types#VARCHAR}
*/
public static int getNullType(PreparedStatement statement, int paramIndex) {
int sqlType = Types.VARCHAR;
final ParameterMetaData pmd;
try {
pmd = statement.getParameterMetaData();
sqlType = pmd.getParameterType(paramIndex);
ParameterMetaData pmd = statement.getParameterMetaData();
return pmd.getParameterType(paramIndex);
} catch (SQLException ignore) {
return Types.VARCHAR;
}
return sqlType;
}
/**
+2 -2
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.1</version>
<version>0.3.3</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -22,7 +22,7 @@
<artifactId>easysql-demo</artifactId>
<packaging>jar</packaging>
<name>99-EasySQL-Demo</name>
<name>EasySQL-Demo</name>
<description>EasySQL的演示部分</description>
<url>https://github.com/CarmJos/EasySQL</url>
+2 -2
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.1</version>
<version>0.3.3</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -21,7 +21,7 @@
<artifactId>easysql-test</artifactId>
<name>98-EasySQL-Demo</name>
<name>EasySQL-Test</name>
<description>EasySQL的测试代码</description>
<url>https://github.com/CarmJos/EasySQL</url>
@@ -2,22 +2,24 @@ package cc.carm.lib.easysql.testrunner;
import cc.carm.lib.easysql.EasySQL;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.testrunner.tests.TableAlterTest;
import cc.carm.lib.easysql.testrunner.tests.QueryCloseTest;
import cc.carm.lib.easysql.testrunner.tests.QueryFunctionTest;
import cc.carm.lib.easysql.testrunner.tests.TableCreateTest;
import cc.carm.lib.easysql.testrunner.tests.TableRenameTest;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
@TestOnly
@SuppressWarnings("all")
public class Main {
public static void main(String[] args) {
if (args.length < 4) {
print("请提供以下参数: 数据库地址 数据库用户数据库密码");
print("请提供以下参数:<数据库驱动> <数据库地址(JDBC)> <数据库用户> <数据库密码> [是否采用DEBUG(y/n)]");
return;
}
@@ -40,8 +42,13 @@ public class Main {
print("加载测试类...");
Set<EasySQLTest> tests = new LinkedHashSet<>();
tests.add(new TableCreateTest());
tests.add(new TableAlterTest());
tests.add(new TableRenameTest());
// tests.add(new TableAlterTest());
// tests.add(new TableRenameTest());
// tests.add(new QueryNotCloseTest());
tests.add(new QueryCloseTest());
// tests.add(new SQLUpdateBatchTests());
// tests.add(new SQLUpdateReturnKeysTest());
tests.add(new QueryFunctionTest());
print("准备进行测试...");
@@ -73,21 +80,12 @@ public class Main {
success, (tests.size() - success)
);
}
EasySQL.shutdownManager(sqlManager);
}
public static void print(@NotNull String format, Object... params) {
System.out.printf((format) + "%n", params);
}
public static @Nullable EasySQLTest cast(@NotNull Class<?> value) {
if (!EasySQLTest.class.isAssignableFrom(value)) return null;
try {
return (EasySQLTest) value.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
return null;
}
}
}
@@ -0,0 +1,31 @@
package cc.carm.lib.easysql.testrunner.tests;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.testrunner.EasySQLTest;
import java.sql.ResultSet;
import java.sql.SQLException;
public class QueryCloseTest extends EasySQLTest {
@Override
public void onTest(SQLManager sqlManager) throws SQLException {
try (SQLQuery query = sqlManager.createQuery()
.inTable("test_user_table")
.orderBy("id", false)
.setLimit(5)
.build().execute()) {
ResultSet resultSet = query.getResultSet();
while (resultSet.next()) {
System.out.println("id: " + resultSet.getInt("id") + " username: " + resultSet.getString("username"));
}
}
}
}
@@ -0,0 +1,34 @@
package cc.carm.lib.easysql.testrunner.tests;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.testrunner.EasySQLTest;
import java.sql.SQLException;
public class QueryFunctionTest extends EasySQLTest {
@Override
public void onTest(SQLManager sqlManager) throws SQLException {
Integer id_1 = sqlManager.createQuery()
.inTable("test_user_table")
.orderBy("id", false)
.setLimit(1)
.build().executeFunction(query -> {
if (!query.getResultSet().next()) return -1;
else return query.getResultSet().getInt("id");
});
System.out.println("id (ps): " + id_1);
Integer id_2 = sqlManager.createQuery().withSQL("SELECT id FROM test_user_table ORDER BY id DESC LIMIT 1")
.executeFunction(query -> {
if (!query.getResultSet().next()) return -1;
else return query.getResultSet().getInt("id");
});
System.out.println("id (s): " + id_2);
}
}
@@ -0,0 +1,30 @@
package cc.carm.lib.easysql.testrunner.tests;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.testrunner.EasySQLTest;
import java.sql.ResultSet;
import java.sql.SQLException;
public class QueryNotCloseTest extends EasySQLTest {
@Override
public void onTest(SQLManager sqlManager) throws SQLException {
SQLQuery query = sqlManager.createQuery()
.inTable("test_user_table")
.orderBy("id", false)
.setLimit(5)
.build().execute();
ResultSet resultSet = query.getResultSet();
while (resultSet.next()) {
System.out.println("id: " + resultSet.getInt("id") + " username: " + resultSet.getString("username"));
}
}
}
@@ -0,0 +1,38 @@
package cc.carm.lib.easysql.testrunner.tests;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.testrunner.EasySQLTest;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SQLUpdateBatchTests extends EasySQLTest {
@Override
public void onTest(SQLManager sqlManager) throws SQLException {
List<Integer> updates = sqlManager.createInsertBatch("test_user_table")
.setColumnNames("uuid", "username", "age")
.setAllParams(generateParams())
.execute();
System.out.println("changes " + Arrays.toString(updates.toArray()));
}
protected List<Object[]> generateParams() {
return IntStream.range(0, 5).mapToObj(i -> generateParam()).collect(Collectors.toList());
}
protected Object[] generateParam() {
UUID uuid = UUID.randomUUID();
return new Object[]{uuid, uuid.toString().substring(0, 5), (int) (Math.random() * 50)};
}
}
@@ -0,0 +1,24 @@
package cc.carm.lib.easysql.testrunner.tests;
import cc.carm.lib.easysql.api.SQLManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
public class SQLUpdateReturnKeysTest extends SQLUpdateBatchTests {
@Override
public void onTest(SQLManager sqlManager) throws SQLException {
List<Integer> generatedKeys = sqlManager.createInsertBatch("test_user_table")
.setColumnNames("uuid", "username", "age")
.setAllParams(generateParams())
.returnGeneratedKeys()
.execute();
System.out.println("generated " + Arrays.toString(generatedKeys.toArray()));
}
}
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="cc.carm.lib.easysql">
<Appenders>
<console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n"/>
</console>
<RollingRandomAccessFile name="File" fileName="logs/latest.log" filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<OnStartupTriggeringPolicy/>
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<root level="info">
<filters>
<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY" onMismatch="NEUTRAL"/>
</filters>
<!-- <AppenderRef ref="WINDOWS_COMPAT" level="info"/>-->
<AppenderRef ref="File"/>
<appender-ref ref="Console"/>
</root>
</Loggers>
</Configuration>
+5 -6
View File
@@ -16,7 +16,7 @@
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId>
<packaging>pom</packaging>
<version>0.3.1</version>
<version>0.3.3</version>
<modules>
<module>easysql-api</module>
@@ -153,7 +153,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.1</version>
<version>2.5.3</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<useReleaseProfile>false</useReleaseProfile>
@@ -169,7 +169,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<version>3.3.1</version>
<configuration>
<classifier>javadoc</classifier>
<detectJavaApiLink>false</detectJavaApiLink>
@@ -181,7 +181,6 @@
<includeDependencySources>true</includeDependencySources>
<dependencySourceIncludes>
<dependencySourceInclude>cc.carm.lib:*</dependencySourceInclude>
<dependencySourceInclude>cn.beecp:*</dependencySourceInclude>
</dependencySourceIncludes>
</configuration>
<executions>
@@ -197,7 +196,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.9.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@@ -209,7 +208,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<version>3.2.2</version>
</plugin>
<plugin>
+3 -3
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.1</version>
<version>0.3.3</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -20,7 +20,7 @@
<artifactId>easysql-beecp</artifactId>
<packaging>jar</packaging>
<name>12-EasySQL-BeeCP</name>
<name>EasySQL-BeeCP</name>
<description>EasySQL的应用部分。此为BeeCP版本。</description>
<url>https://github.com/CarmJos/EasySQL</url>
@@ -73,7 +73,7 @@
<!--项目地址 https://github.com/Chris2018998/BeeCP -->
<groupId>com.github.chris2018998</groupId>
<artifactId>beecp</artifactId>
<version>3.3.0</version>
<version>3.3.1</version>
<optional>true</optional>
<scope>compile</scope>
</dependency>
+2 -2
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.1</version>
<version>0.3.3</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -19,7 +19,7 @@
<artifactId>easysql-hikaricp</artifactId>
<name>11-EasySQL-HikariCP</name>
<name>EasySQL-HikariCP</name>
<description>EasySQL的应用部分。此为HikariCP版本。</description>
<url>https://github.com/CarmJos/EasySQL</url>