Inserting records into a MySQL table using Java

后端 未结 4 2128
北海茫月
北海茫月 2021-02-13 14:45

I created a database with one table in MySQL:

CREATE DATABASE iac_enrollment_system;

USE iac_enrollment_system;

CREATE TABLE course(
    course_code CHAR(7),
          


        
4条回答
  •  旧时难觅i
    2021-02-13 15:07

    no that cannot work(not with real data):

    String sql = "INSERT INTO course " +
            "VALUES (course_code, course_desc, course_chair)";
        stmt.executeUpdate(sql);
    

    change it to:

    String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
            "VALUES (?, ?, ?)";
    

    Create a PreparedStatment with that sql and insert the values with index:

    PreparedStatement preparedStatement = conn.prepareStatement(sql);
    preparedStatement.setString(1, "Test");
    preparedStatement.setString(2, "Test2");
    preparedStatement.setString(3, "Test3");
    preparedStatement.executeUpdate(); 
    

提交回复
热议问题