有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);
        }
    }

共 (4) 个答案

  1. # 1 楼答案

    你也可以用try-catch

    try {
        // try to convert to number if it's integer
        Long number = Long.valueOf("number");
             
        // without question
        sqlStatement+=" DEFAULT "+ number; 
    
    } catch (Exception ignored){
        // default value or string with question
        sqlStatement+=" DEFAULT "+this.defaultValue;
    }
    

    更新

    也可以是这样

    Long number = null;
    try {
        Long number = Long.valueOf("string number");
    } catch (Exception ignored){}
    
    // #1 if you have just number field
    sqlStatement+= number != null ? number : this.defaultValue;
    
    // #2 Or if want to use question
    if(number != null)
        sqlStatement+= number       // without question
    else
        sqlStatement+= " DEFAULT "  // without question
    
  2. # 2 楼答案

    String s = "Example String";
    if (s.matches("[0-9]+")) {
      System.out.println("Only numbers");
    }else{
      System.out.println("Contains spaces or letters");
    }
    
  3. # 3 楼答案

    可以使用正则表达式

    String str=" your string 123";
    if(str.matches("[0-9]+")){
    //Do something
    }
    
  4. # 4 楼答案

    这不是您应该如何构造SQL的,因为它使您对SQL injection attacks敞开大门

    您应该改用JDBCPreparedStatement类。这使您可以在需要参数的地方使用?字符编写SQL,然后以编程方式设置值。它处理所有适当的转义以防止SQL注入

    这是Oracle Java Tutorial for Prepared Statements