java 如何使用Java将数据插入到mysql中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12760069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert data into mysql using Java
提问by black_belt
I am trying to insert data into mysql database using Java. I am using the following code to fetch data from database and it is working fine.
我正在尝试使用 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));
}
}
}
To Insert data, I have tried the above code only replacing
要插入数据,我已经尝试了上面的代码只替换
PreparedStatement statement= con.prepareStatement("SELECT * FROM jam
WHERE id='1'");
with
和
PreparedStatement statement= con.prepareStatement("INSERT INTO jam(id,name)
VALUES ('','Charlie Sheen')");
But its showing some errors. Could you please tell me where is the problem in my code.
但它显示了一些错误。你能告诉我我的代码中的问题在哪里吗?
Thanks :)
谢谢 :)
回答by mstzn
If your primary key is auto increment,you can try this;
如果你的主键是自动递增的,你可以试试这个;
PreparedStatement statement= con.prepareStatement("INSERT INTO jam(name)
VALUES (?)");
statement.setString(1,"Charlie Sheen");
statement.execute();
回答by Anshu
If you have to insert lots of records, use 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();??
回答by Gianmarco
I think you can also use this (if the ID is auto-increment)
我想你也可以使用这个(如果 ID 是自动递增的)
"INSERT INTO jam(name) VALUES ('Charlie Sheen')"
in any case, If you do not know the value of a specific int field I suggest not to write it into the query, it will be setted by default.
无论如何,如果您不知道特定 int 字段的值,我建议不要将其写入查询中,它将默认设置。
I think, if you set and INTEGER column = '', it could be a problem to the mysql.
我想,如果你设置了INTEGER column='',那可能是mysql的问题。
usually, I do not put numbers inside the ->''
通常,我不会将数字放在 ->''
回答by nagendra babu
@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();
}