简体   繁体   中英

Parse/Split a string and upload it into the database

I am trying to split/parse a string into several parts and then correctly upload it into the database.

I have a string like that :

String CARDS =
        "e \"Water\"\n" +
        "n \"John\"\n" +
        "p \"Big\"\n" +
        "e \"Fire\"\n";

I want to separate each line and have something like

 e
 "Water"
 n
 "John"

I managed to do it by with something like this :

      String delim = " \n\r\t,.;"; //insert here all delimitators
      StringTokenizer card = new StringTokenizer(CARDS,delim);
      while (card.hasMoreTokens()) {
          System.out.println(card.nextToken());
      }

I have created a small table called card which contains card_type and card_desc. Where the card_type would be the first letter like e, n etc and then the card_desc would be Water , John etc.

I also have an insert method :

public void insert() throws SQLException {
    Connection con = ListPlayers.myCon.get();
    String query = "INSERT INTO deck (card_type,card_desc) VALUES (?,?);";
    PreparedStatement ps = con.prepareStatement(query);
    ps.setString(1, card_type);
    ps.setString(2, card_desc);
    ps.executeUpdate();
    ps.close();
}

I am just not sure how to succesfully divide the splited string into card type and desc and then upload it to the database.

You have already done the hard part. Just replace the quotes (") from your description and call your method to insert the data. Update your while loop.

while (card.hasMoreTokens()) {
    String card_type = card.nextToken();
    String card_desc = card.nextToken().replace("\"","");
    //you can call your insert method to insert the data
    // example insert(card_type,card_desc)
    System.out.println(card_type+"::"+card_desc);
}

I have added the print just to test.

Update your insert method to pass the parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM