1. 程式人生 > 資料庫 >使用Jdbc批量新增資料庫資料

使用Jdbc批量新增資料庫資料

1.建立類

 

public class JDBC {
public static void main(String[] args) {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    //模擬批量的資料    
    Person person1 = new Person();
    person1.setName("李天佑");
    person1.setAge(20);

    Person person2 = new Person();
    person2.setName("劉一手");
    person2.setAge(30);

    Person person3 = new Person();
    person3.setName("劉美美");
    person3.setAge(40);

    //批量新增使用者
    ArrayList<Person> list = new ArrayList<>();
    list.add(person1);
    list.add(person2);
    list.add(person3);
    try {
//1.載入Driver驅動
Class.forName("com.mysql.jdbc.Driver");
//2.建立資料庫連線
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
//3.獲取執行SQL語句的操作物件
String sql = "insert into person(name,age)values(?,?)";  //?代表佔位符,每個?表示每個屬性對應要傳入的引數
statement = connection.prepareStatement(sql);       //這裡使用prepareStatement操作物件,是在執行SQL語句之前,提前編譯SQL語句的格式,防止SQL注入。

//遍歷List集合,將封裝的物件新增到資料庫
for (Person person : list) {
String name = person.getName();
Integer age = person.getAge();
statement.setString(1,name);
statement.setInt(2,age);
//執行SQL語句
statement.executeUpdate();  //executeQuery()方法是SQL語句是查詢的時候使用executeQuery()。SQL語句在執行新增/更新/刪除資料時使用executeUpdate();
            }
} catch (Exception e) {
e.printStackTrace();
}finally {
//關閉連線物件
if (resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

2.批量新增成功後,資料庫的變化。
以下紅框裡面的3條記錄是一次性批量新增的