如何将用户输入分配为变量并将该变量存储在我的数据库中?

时间:2016-11-09 18:30:45

标签: java mysql

我试图从用户那里获取6个变量的值,然后将这些输入存储在数据库中。如何编写它以将用户输入设置为变量?

所以我想将变量num1等设置为用户输入。

我的代码是=>

公共课LottoJDBC {

private Connection connection;

public LottoJDBC() throws Exception

//CONNECT TO DATABASE

{
    Class.forName("com.mysql.lottoPro.Driver").newInstance();
    connection = DriverManager.getConnection("lottoPro:mysql://localhost:3306/lottProDB"+"user=root&password=root");

    //SELECT DATA FROM DATABASE
    Statement select = connection.createStatement();
    ResultSet rs = select.executeQuery("SELECT * FROM userChoice");
    while (rs.next()) {
    System.out.println("These numbers are already taken by the previous user: "+rs.getNString(1) + " " +rs.getNString(2) + " " +rs.getNString(3) + " " +rs.getNString(4) + " " +rs.getNString(5) + " " +rs.getNString(6) + ".");

    }


    //INSERTTING DATA
    try (PreparedStatement createUser = connection.prepareStatement("INSERT into userChoice (num1, num2, num3, num4, num5, num6)" + " VALUES ( ?, ?, ?, ?, ?, ?)")) {
        int num1, num2, num3, num4, num5, num6;
        createUser.setInt(1, num1);
        createUser.setInt(2, num2);
        createUser.setInt(3, num3);
        createUser.setInt(4, num4);
        createUser.setInt(5, num5);
        createUser.setInt(6, num6);
        int rowsUpdated = createUser.executeUpdate();
        createUser.close();
    }

    connection.close();
}

    public static void main(String[] args){
        try {
            new LottoJDBC();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用Scanner类,如there所述,可能还有很多其他地方。

一旦程序运行" reader.nextInt();"行,您的程序将停止并提示用户输入控制台中的条目。话虽如此,您将需要检查用户输入的数据,因为有人可能想输入无效的条目(如字母)以查看发生的情况(在这种情况下,它会抛出异常)。

答案 1 :(得分:0)

不是最理想的方式,但肯定会让您了解有关获取用户输入的问题。

public class LottoJDBC {
        private static int num1;
        private static int num2;
        private static int num3;
        private static int num4;
        private static int num5;
        private static int num6;

        public LottoJDBC() throws Exception

        {
            System.out.println(num1);
            System.out.println(num2);
            System.out.println(num3);
            System.out.println(num4);
            System.out.println(num5);
            System.out.println(num6);
        }

        public static void main(String[] args){
            try {
                Scanner scanner = new Scanner(System.in);

                num1 = scanner.nextInt();
                num2 = scanner.nextInt();
                num3 = scanner.nextInt();
                num4 = scanner.nextInt();
                num5 = scanner.nextInt();
                num6 = scanner.nextInt();

                new LottoJDBC();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }