-2

I need to insert multiple chars into a database table, the code below inserts one random char(in two different ways) in every table row. But i need like 10 different chars in every row. How can i do that?

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()) + "'" +
                        ")") ;


            }
Marius V
  • 13
  • 3
  • you could make a method that returns a String of random characters, with a length of your choosing. – 4dc0 Apr 26 '17 at 19:10

1 Answers1

0

it's always advisable that you try to do it on your own, we learn by practicing. however, you can have a look at this static method which returns a random string of number of chars specified by you:

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

example:

randomString(1) -> output: r
randomString(5) -> output: eoucv
randomString(26) -> output: unaetqsycmwjplizhdfkrvoxbg
Yahya
  • 13,349
  • 6
  • 30
  • 42