Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Java将数据插入mysql_Java_Mysql - Fatal编程技术网

如何使用Java将数据插入mysql

如何使用Java将数据插入mysql,java,mysql,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 Exceptio

我正在尝试使用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(name) 
     VALUES (?)");

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

statement.execute();

如果你的主键是自动递增,你可以试试这个

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

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

statement.execute();

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

    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();  

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

    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();  

如果ID是自动递增的,我想你也可以使用它

"INSERT INTO jam(name) VALUES ('Charlie Sheen')"
在任何情况下,如果您不知道特定int字段的值,我建议不要将其写入查询中,它将默认设置

我认为,如果设置和INTEGER column=,可能会给mysql带来问题


通常,我不会将数字放在->

中,我认为如果ID是自动递增的,您也可以使用它

"INSERT INTO jam(name) VALUES ('Charlie Sheen')"
@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();
    }
在任何情况下,如果您不知道特定int字段的值,我建议不要将其写入查询中,它将默认设置

我认为,如果设置和INTEGER column=,可能会给mysql带来问题


通常,我没有在->

中输入数字,您会遇到什么错误?请也指定错误。如果您使用诸如Hibernate之类的ORM框架而不是JDBC,则与来自Java的数据库交谈会容易得多。您会遇到什么错误?请也指定错误。如果您使用诸如Hibernate之类的ORM框架,则与来自Java的数据库交谈会容易得多Hibernate而不是JDBC。在实际应用程序中,使用这样的绑定参数非常重要,因为数据由最终用户提供。谷歌小波比表幽默地看看为什么会这样。另外,statement.executeUpdate而不是execute将为您提供实际插入行数的计数,尽管这在执行更新时比执行插入时更重要。@mstzn非常感谢。它现在正在工作。我是否应该使用statement.execute;也用于更新数据库?statement.execute=>如果您不知道要使用哪个方法来执行SQL语句,可以使用此方法。statement.executeUpdate=>通常是drob表或数据库,插入到表中,更新表,在实际应用程序中,使用像这样的绑定参数非常重要,因为数据是由最终用户提供的。谷歌小波比表幽默地看看为什么会这样。另外,statement.executeUpdate而不是execute将为您提供实际插入行数的计数,尽管这在执行更新时比执行插入时更重要。@mstzn非常感谢。它现在正在工作。我是否应该使用statement.execute;也用于更新数据库?statement.execute=>如果您不知道要使用哪种方法来执行SQL语句,可以使用此方法。statement.executeUpdate=>通常情况下,drob table或database、insert into table、update table、delete from table语句将在此过程中使用。
@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();
    }