将多个随机字符插入数据库表JAVA

时间:2017-04-26 19:06:08

标签: java database random

我需要在数据库表中插入多个字符,下面的代码在每个表行中插入一个随机字符(以两种不同的方式)。但我需要每排10个不同的字符。我怎样才能做到这一点?

public static void insertToTable2(Connection c, String tableName, int numberOfRows) throws UnsupportedEncodingException, SQLException {
            Random rand = new Random();
            String chars = "abcdf";
            StringBuilder sql =
                    new StringBuilder("INSERT INTO " + tableName + " (NR,PIRMAS1,ANTRAS1,TRECIAS1,KETVIRTAS1,PENKTAS1,SESTAS1,SEPTINTAS1,ASTUNTAS1,DEVINTAS1) VALUES ");

            for (int j=0; j < numberOfRows; j++)
            {
                if (j != 0) sql.append (",");
                sql.append ("(" + j +
                        ",'" + chars.charAt(rand.nextInt(chars.length())) + "'" +
                        ",'" + chars.charAt(rand.nextInt(chars.length())) + "'" +
                        ",'" + (char)(rand.nextInt(25)+65) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ")") ;


            }

1 个答案:

答案 0 :(得分:0)

总是建议你自己尝试,我们通过练习来学习。 但是,您可以查看此静态方法,该方法返回由您指定的字符数量的随机字符串:

public static String randomString(int lenOfString){
  String s = "abcdefghijklmnopqrstuvwxyz";
  String randString= "";
  if (lenOfString<=26){
     List<Integer> indexRef = new ArrayList<Integer>();
     for(int i=0; i<s.length(); i++){
            indexRef.add(i);
     }
     Random rnd = new Random();
     for (int i=0; i<lenOfString; i++){
         int index = indexRef.get(rnd.nextInt(indexRef.size()));
         randString+= s.charAt(index);
         indexRef.remove(indexRef.indexOf(index));
     }
  }
  return randString;
}

示例:

randomString(1) -> output: r
randomString(5) -> output: eoucv
randomString(26) -> output: unaetqsycmwjplizhdfkrvoxbg