2

I am trying to insert user Input from the console into a Json object & then trying to insert the same into MySQL. I am not sure how I can achieve this! I have a main method that reads from the console & writes it to Json.

public static void main(String... args)
{
    Map<String,String> myMap = new HashMap<String,String>();

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your name;");
    String firstName = sc.next();
    myMap.put("firstName",firstName);

    Scanner sc1 = new Scanner(System.in);
    System.out.println("Enter your lastName;");
    String lastName = sc1.next();
    myMap.put("lastName",lastName);

    Scanner sc2 = new Scanner(System.in);
    System.out.println("Enter your email;");
    String email = sc2.next();
    myMap.put("email",email);

    Scanner sc3 = new Scanner(System.in);
    System.out.println("Enter your mobile;");
    String mobile = sc3.next();
    myMap.put("mobile",mobile);

    try {
        JSONObject jsonObject = new JSONObject(myMap.toString());
        System.out.println(jsonObject.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

I have written a method whereby I am able to enter values that are hard coded from my code.

static UserInfo jsonToUser(){
    String json = "{"
        + "firstName: \"Aaron\","
        + "lastName: \"Ramsey\","
        + "mobile: \"1234\","
        + "email: \"test@test.com\""
        + "}";

    Gson g = new Gson();
    UserInfo user = g.fromJson(json, UserInfo.class);

    //System.out.println(user);
    return user;
}

What I am trying to do is, enter the values from the console into a Json & then from that Json to the DB . Could someone give me a hint or Idea as to how to achieve this? Many thanks.

AdiBoy
  • 145
  • 7
  • 20
  • You already have the json as a ``String``. What have you tried so far to write the ``String`` into a database? – f1sh Mar 03 '16 at 08:08
  • I think you should try JDBC for java – Jorgovanka Mar 03 '16 at 08:13
  • @f1sh : I am able to insert hard coded data into the DB. Connection con = DBHelper.getConnection(p); UserInfo user = jsonToUser(); //System.out.println(user); String ins = "insert into Student (firstName,lastName, mobile, email) values (?,?,?,?)"; //DBHelper.insert(con, ins, user.getFirstName(), user.getLastName(), user.getMobile(), user.getEmail()); DBHelper.executeQuery(con, "select * from Student"); DBHelper.close(con); But, I want the console data to be inserted into DB through the JSON – AdiBoy Mar 03 '16 at 08:28
  • What's stopping you from connecting those two pieces of code? – f1sh Mar 03 '16 at 08:31
  • http://stackoverflow.com/questions/31130385/best-way-to-insert-json-data-into-mysql have you checked this – RishiKesh Pathak Mar 03 '16 at 08:38

0 Answers0