简体   繁体   English

在mysql insert语句中使用Java变量作为值

[英]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. 我目前有两种创建的方法,一种名为createDatabase,用于创建mysql数据库,表并将值插入该表。 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. 我正在努力地了解如何将变量从userInput方法传递给createDatabase方法,以及如何将变量用作insert语句的值。

Here is the createDatabase method 这是createDatabase方法

  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 userInput方法

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: 要插入记录,您应该使用PreparedStatement防止SQL注入:

    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. 串联String来形成SQL语句从来都不是一个好选择,它会在您的应用程序中创建一个安全漏洞,并且当老板被利用时会被劫持。

If you do this in Java, I recommend following Object Oriented principles. 如果您使用Java进行此操作,建议您遵循面向对象的原则。 Do not write Java code like is C. You can create a Person object that has the following fields: 不要像C一样编写Java代码。您可以创建具有以下字段的Person对象:

    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 之后在userInput中写

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

As a consequence the userInput now return an instance of Person. 结果,userInput现在返回Person的实例。 Split the createDatabase method in 2 parts: First method should handle the database creation The second method should handle the insertion. 将createDatabase方法分为两部分:第一个方法应处理数据库的创建第二个方法应处理插入。 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. 结论: 请学习Java准则和原则,然后尝试用它来构建某些东西,因为如果您学习它是愚蠢的,那么您将使用它是愚蠢的。 Sorry if any offense! 对不起,如果有任何冒犯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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