简体   繁体   English

如何使用 java 变量将值插入 mysql

[英]How to insert values to mysql using java variables

I am working with CLI Student Registration sample system.我正在使用 CLI 学生注册示例系统。 I want to connect the database with the CLI.我想用 CLI 连接数据库。 I'm using MYSQL and Java for that.我为此使用 MYSQL 和 Java 。 After running the below code an exception is shown like that:运行以下代码后,会显示如下异常:

public class Student_Registration {
    String name,uname,pwd;
    int age, select;
    public void input() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome to University Management System\n\n....\nStudent Registration");
        System.out.println("Please Submit the following information,\nName: ");
        name = sc.next();
        System.out.println("Username: ");
        uname = sc.next();
        System.out.println("Password: ");
        pwd = sc.next();
        System.out.println("Age: ");
        age = sc.nextInt();
        System.out.println("Select Course Number from following list");
        System.out.println("[1] SENG 11111 - Introduction to Programming");
        System.out.println("[2] SENG 11112 - Fundamentals of Engineering");
        System.out.println("[3] SENG 11113 - Data Structures and Algorithms");
        select = sc.nextInt();
    }
    public void add(){
        try{
           Class.forName("com.mysql.jdbc.Driver");
           Connection con = DriverManager.getConnection(
                   "jdbc:mysql://localhost:3306/mydatabase", "root", "Luxan@22"
           );
           Statement st = con.createStatement();
           st.executeUpdate("INSERT INTO emp (Username, Name, Age, Password) VALUES ("+uname+","+ name +","+ age +","+ pwd+")");
           con.close();

        }catch (Exception e){System.out.println(e);}
    }
    public void Display() {
        System.out.println("You have successfully registered for the followuing course: ");
       try {
           Class.forName("com.mysql.jdbc.Driver");
           Connection con = DriverManager.getConnection(
                   "jdbc:mysql://localhost:3306/mydatabase", "root", "Luxan@22"
           );
           Statement sta = con.createStatement();
        switch(select) {
            case 1:
                System.out.println("Subject: SENG 11111 - Introduction to Programming");
                sta.executeUpdate("INSERT INTO course (username,course) VALUES ("+uname+","+ "'Subject: SENG 11111 - Introduction to Programming')");
                break;
            case 2:
                System.out.println("Subject: SENG 11112 - Fundamentals of Engineering");
                sta.executeUpdate("INSERT INTO course (username,course) VALUES ("+uname+","+" 'Subject: SENG 11112 - Fundamentals of Engineering')");
                break;

            case 3:
                System.out.println("Subject: SENG 11113 - Data Structures and Algorithms");
                sta.executeUpdate("INSERT INTO course (username,course) VALUES ("+uname+","+" 'Subject: SENG 11113 - Data Structures and Algorithms')");
                break;
        }
        con.close();
    }catch(Exception e) {System.out.println(e);}
       System.out.println("Thank You");
    }
}

There is no issue with the no.of columns and related names in the table.表中的列数和相关名称没有问题。 The exception states as below:异常状态如下:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'luxan' in 'field list'
You have successfully registered for the followuing course: 
Fri Nov 22 15:21:33 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Subject: SENG 11111 - Introduction to Programming
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'luxan' in 'field list'

The inputs I entered are:我输入的输入是:

Name: Thiluxan
Username: luxan
password: 1234
Age: 21

You are not escaping the values correctly which causes an error with the INSERT statement.您不是 escaping 正确的值,这会导致 INSERT 语句出错。 In your example luxan should be quoted with ' as 'luxan' to indicate it's a text constant and not a column name.在您的示例中, luxan应该用' as 'luxan'引用,以表明它是文本常量而不是列名。 This lack of escaping also makes your code vulnerable to SQL Injection attack .缺少 escaping 也使您的代码容易受到SQL 注入攻击

To address both problems you should use PreparedStatements as per docs :.要解决这两个问题,您应该按照文档使用PreparedStatements :.

PreparedStatements st = con.prepareStatement(
    "INSERT INTO emp (Username, Name, Age, Password) VALUES (?, ?, ?, ?)");
st.setString(1, uname);
st.setName(2, name);
st.setInt(3, age);
st.setString(4, pwd);
st.executeUpdate();
String SQL_INSERT = "INSERT INTO emp (Username, Name, Age, Password) VALUES (?,?,?,?);
try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/mydatabase", "root", "Luxan@22");
             PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT)) {

            preparedStatement.setString(1, username);
            preparedStatement.setString(2, name);
            preparedStatement.setInt(3, age);
            preparedStatement.setString(4, pwd);

            int row = preparedStatement.executeUpdate();

            // rows affected
            System.out.println(row); //1

        } catch (SQLException e) {
            System.err.format("SQL State: %s \n %s", e.getSQLState(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

no need to use class for name because in new version driver class will be automatically detected.无需使用 class 作为名称,因为在新版本驱动程序中会自动检测 class。 use prepared statement instead of statement使用准备好的语句而不是语句

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

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