简体   繁体   中英

Using java variables as values in mysql insert statement

I currently have two created methods, one named createDatabase which creates a mysql database, table and inserts values into that table. The second method collects data from the user and stores them in variables.

I'm struggling to know how it would be possible to pass the variables from the userInput method to the createDatabase method, And how to then use the variables as values for the insert statement.

Here is the createDatabase method

  public void createDatabase(){
    String data = "jdbc:mysql://localhost:3306/?user=root&password=root";
    try {

         Class.forName("com.mysql.jdbc.Driver");


        Connection conn = DriverManager.getConnection(data);
        Statement st = conn.createStatement();
        System.out.println("Connection made");

        int result = st.executeUpdate("DROP DATABASE IF EXISTS TESTDATABASE");

        result = st.executeUpdate("CREATE DATABASE TESTDATABASE");

        result = st.executeUpdate("USE TESTDATABASE");

        result = st.executeUpdate(
                "CREATE TABLE testtable ("
                + "dex INT NOT NULL AUTO_INCREMENT PRIMARY KEY, "
                + "name VARCHAR(40), "
                + "address1 VARCHAR(40), "
                + "address2 VARCHAR(40), "
                + "phone VARCHAR(20), "
                + "email VARCHAR(40))");
        result = st.executeUpdate(
                "INSERT INTO testtable(name, address1, address2, "
                + "phone, email) VALUES("
                + "'+name+', "
                + "'+address1+', "
                + "'+address2+', "
                + "'+phone+', "
                + "'+email+')"); 

        st.close();
        System.out.println("Database Created");
    }   catch (Exception e) {
            System.out.println("Error -- " + e.toString());
    }

}

The userInput method

public void userInput(){
    String name;
    String address1;
    String address2;
    String phone;
    String email;

    Scanner in = new Scanner(System.in); 

    System.out.println("Enter name");
    name = in.nextLine();
    System.out.println("Enter first line of address");
    address1 = in.nextLine();
    System.out.println("Enter second line of address");
    address2 = in.nextLine();
    System.out.println("Enter phone number");
    phone = in.nextLine();
    System.out.println("Enter email address");
    email = in.nextLine();
    System.out.println("Details collected");

}

And main

public static void main(String[] arguments) {
    TestDatabase test = new TestDatabase();
    test.userInput();
    test.createDatabase();

}

Any help and suggestions thanks!

To insert the record you should use a PreparedStatement to protect against SQL injection:

    try{
        String sql = "INSERT INTO testtable(name, address1, address2,phone, email)VALUES(?,?,?,?,?)"
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1,name);
        statement.setString(2,address1);
        statement.setString(3, address2);
        statement.setString(4, phone);
        statement.setString(5, email);
        statement.executeUpdate();
     }catch(SQLException e){

     }

Concatenating String s to form a SQL statement is never a good option, it creates a security vulnerability in your application and your boss will be jacked when its exploited.

If you do this in Java, I recommend following Object Oriented principles. Do not write Java code like is C. You can create a Person object that has the following fields:

    private String name;
    private String address1;
    private String address2;
    private String phone;
    private String email;

constructor

 Person(String name, String address1, String address2, String phone, String email) {
        this.name = name;
        this.address1 = address1;
        this.address2 = address2;
        this.phone = phone;
        this.email = email;
    }

and getters like

public String getName() {
    return this.name;
}

for each attribute. After that in userInput write

return new Person(name, address1, address2, phone, email);

As a consequence the userInput now return an instance of Person. Split the createDatabase method in 2 parts: First method should handle the database creation The second method should handle the insertion. Example

public void insertInDatabase(Statement st, Person p) {
   // here you can use code that others have posted.
}

As a conclusion: Please learn Java guidelines and principles and after that try to build something with it, because if you learn it stupid, you will use it stupid. Sorry if any offense!

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