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);
}
}
# 1 楼答案
你也可以用try-catch
更新
也可以是这样
# 2 楼答案
# 3 楼答案
可以使用正则表达式
# 4 楼答案
这不是您应该如何构造SQL的,因为它使您对SQL injection attacks敞开大门
您应该改用JDBC
PreparedStatement
类。这使您可以在需要参数的地方使用?
字符编写SQL,然后以编程方式设置值。它处理所有适当的转义以防止SQL注入这是Oracle Java Tutorial for Prepared Statements