如何使用Java将数据插入mysql

时间:2012-10-06 13:08:26

标签: java mysql

我正在尝试使用Java将数据插入到mysql数据库中。我使用以下代码从数据库中获取数据,它工作正常。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DbTest {

public static void main (String[] args) throws Exception{


    // Accessing Driver From Jar File
    Class.forName("com.mysql.jdbc.Driver");

    //DB Connection
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");  

    // MySQL Query
    PreparedStatement statement= con.prepareStatement("SELECT * FROM jam WHERE id='1'");

    //Creating Variable to execute query
    ResultSet result=statement.executeQuery();

    while(result.next()){

        System.out.println(result.getString(2));

    }

  }


  }

要插入数据,我已尝试上述代码仅替换

PreparedStatement statement= con.prepareStatement("SELECT * FROM jam 
 WHERE id='1'");

 PreparedStatement statement= con.prepareStatement("INSERT INTO jam(id,name) 
 VALUES ('','Charlie Sheen')");

但它显示出一些错误。你能否告诉我我的代码中的问题在哪里?

谢谢:)

4 个答案:

答案 0 :(得分:4)

如果您的主键是自动增量,则可以尝试此操作;

  PreparedStatement statement= con.prepareStatement("INSERT INTO jam(name) 
     VALUES (?)");

    statement.setString(1,"Charlie Sheen");

statement.execute();

答案 1 :(得分:1)

如果必须插入大量记录,请使用批量插入

    import java.sql.Connection;
    import java.sql.PreparedStatement;
     
    //...
     
    String sql = "INSERT INTO jam(id, name) VALUES (?, ?)";
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");  
 PreparedStatement ps = connection.prepareStatement(sql);
     
    for (Employee employee: employees) {
        ps.setString(1, employee.getId());
        ps.setString(2, employee.getName());
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();
    connection.close();  

答案 2 :(得分:0)

我认为你也可以使用它(如果ID是自动增量)

"INSERT INTO jam(name) VALUES ('Charlie Sheen')"

在任何情况下,如果您不知道特定int字段的值,我建议不要将其写入查询,默认情况下会设置它。

我认为,如果你设置和INTEGER column ='',它可能是mysql的一个问题。

通常,我不会在 - >''

中添加数字

答案 3 :(得分:0)

@PostMapping("/save")
public void save(@RequestBody EmployeeListModel employeeListModels) throws SQLException{

    Connection connection=MyDataSource.getConnection(); 

     try{

    connection.setAutoCommit(false);
    PreparedStatement statement = connection.prepareStatement("insert into employee(Id,first_name,last_name,email) values (?,?,?,?)");
    List<EmployeeModel> employeeModels = employeeListModels.getModels();

    Iterator<EmployeeModel> iterator = employeeModels.iterator();

    while(iterator.hasNext()){
        EmployeeModel model = iterator.next();
        statement.setInt(1, model.getId());
        statement.setString(2, model.getFirstName());
        statement.setString(3, model.getLastName());
        statement.setString(4, model.getEmail());
        statement.addBatch();

    }

    int[] updates = statement.executeBatch();

    for(int i=0;i<updates.length;i++){
        if(updates[i] == -2){
            System.out.println("executed fail"+i);
        }
        else{
            System.out.println("executed:"+i+"successful"+updates[i]+"updated");
        }


    }

    connection.commit();
    statement.close();
    connection.close();
     }catch (Exception e) {
        e.printStackTrace();
    }