JDBC Batch 批量插入

JdbcBatchInsert.java

import java.sql.*;
public class JdbcBatchInsert {
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);// Disables auto-commit.
st = con.createStatement();
st.addBatch("INSERT INTO person VALUES('4','Komal')");
st.addBatch("INSERT INTO person VALUES('5','Ajay')");
st.addBatch("INSERT INTO person VALUES('6','Santosh')");
st.executeBatch();
String sql = "select * from person";
rs = st.executeQuery(sql);
System.out.println("No \tName");
while (rs.next()) {
System.out.print(rs.getString(1) + " \t");
System.out.println(rs.getString(2));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}




Output
--------------------
No Name
4 Komal
5 Ajay
6 Santosh


JdbcPreparedstatementAddbatch.java

import java.sql.*;

public class JdbcPreparedstatementAddbatch {

public static void main(String args[]) {

Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;

String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";

try {

Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);

pst = con.prepareStatement("insert into lib value(?,?)");
con.setAutoCommit(false);

pst.setString(1, "6");
pst.setString(2, "106");
pst.addBatch();

pst.setString(1, "7");
pst.setString(2, "107");
pst.addBatch();

pst.setString(1, "8");
pst.setString(2, "108");
pst.addBatch();

pst.executeBatch();

pst.close();

String sql = "select * from lib";
pst = con.prepareStatement(sql);

rs = pst.executeQuery();

System.out.println("rno\tlibno");
while (rs.next()) {
System.out.print(rs.getString(1) + " \t");
System.out.println(rs.getString(2));
}
rs.close();
pst.close();
con.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}




Output
----------------------------
Table Name : Employees
Field Type
--------------------
EmployeeID 11
FirstName 50
LastName 50


转自http://www.mytju.com/classcode/news_readNews.asp?newsID=221
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值