java - 如何检查字符串是否只有数字
问题描述
我有这段代码为列添加默认值。如果我的字符串仅由数字组成,它完全可以正常工作,但如果我有其他不是数字的字符(例如:字母,!)SQL 会返回错误,因为引号是必需的。
如何检查字符串是否只有数字?
if(defaultValue!=null)
{
sqlStatement+=" DEFAULT "+this.defaultValue;
}
另外我认为我需要转义引号对吗?我该怎么做?
if (this.getSuffix() != null) {
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.getSuffix())) {
tablesFound = true;
if (!checkColumnsExists(s, tableName)) {
String sql = sqlStatement.replaceAll("name", tableName);
System.out.println("SQL:"+sql);
s.execute(sql);
columnsAdded = true;
}
}
}
}
带有 PreparedStatement 的代码
public void execute(Database database) throws CustomChangeException {
try {
//check if there are any errors in the changelog file
checkArgumentsNumber();
boolean tablesFound = false;
boolean columnsAdded = false;
String sqlStatement = "ALTER TABLE NAME ADD COLUMN " +this.getColumnName()+" "+this.getColumnType();
if(notNull){
sqlStatement+=" NOT NULL";
}
if(defaultValue!=null){
sqlStatement+=" DEFAULT ?";
}
if (this.after != null) {
sqlStatement += " AFTER " +this.after;
}
System.out.println("The statement is: "+sqlStatement);
//get tables in the database
JdbcConnection connection = (JdbcConnection) database.getConnection();
DatabaseMetaData metadata;
metadata = connection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = metadata.getTables(connection.getCatalog(), null, "%", types);
//if the user chose to use a suffix
if (this.getSuffix() != null) {
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.getSuffix())) {
tablesFound = true;
String addStatement=sqlStatement.replaceAll("NAME",tableName);
PreparedStatement s = connection.prepareStatement(addStatement);
if (!checkColumnsExists(s, tableName)) {
if(this.defaultValue!=null){
System.out.println("ENTERED DEFAULT");
s.setString(1,this.defaultValue);
}
s.executeUpdate();
columnsAdded = true;
}
}
}
}
checkInvalidInfo(tablesFound, columnsAdded, "All the matching tables already had that column");
} catch (InvalidArgumentsNumberException | SQLException | InvalidInfoException | DatabaseException e) {
throw new CustomChangeException("Error enabling trigger: " + e);
}
}
解决方案
这不是您应该构造 SQL 的方式,因为它会使您容易受到SQL 注入攻击。
您应该改用 JDBCPreparedStatement
类。这使您可以在需要参数的地方使用字符编写 SQL ?
,然后以编程方式设置值。它处理所有适当的转义以防止 SQL 注入。
推荐阅读
- asp.net-core - 具有现有身份数据库的 Asp.NET Core 和 EF Core
- mysql - MySQL自动将数字转换为字符串(错误)
- r - 使用 Shiny R 获取和显示文件名
- python - 使用 Python 作为 root 用户更新 UNIX 帐户密码的安全方法?
- vue.js - 如何将表单输入的当前值传递给 Vue 组件道具?
- amazon-web-services - AWS Lambda 函数无法发送电子邮件
- python - 在 Python 中估计相关性
- discord - Discord.js - 当有人获得特定角色时触发事件的任何方式?
- ios - iphone应用程序进入后台时注册回调的C API
- firebase - Flutter:数组的 Firebase 映射