package org.sin.common.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.OracleTypes;
import org.sin.domain.User;
public class JDBCDao {
private static boolean mysql = false;
private Connection conn;
static {
try {
if (mysql) {
Class.forName("com.mysql.jdbc.Driver");
} else {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private JDBCDao() {
String url, user, password;
if (mysql) {
url = "jdbc:mysql://127.0.0.1:3306/cl";
user = "root";
password = "";
} else {
url = "jdbc:oracle:thin:@localhost:1521:orcl";
user = "andy";
password = "root";
}
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println(conn.getAutoCommit());
} catch (SQLException e) {
e.printStackTrace();
}
}
private User SaveUser(User user) {
String sql = "insert into t_User(id,username,password) values(user_id.nextval,?,?)";
Long id = -1L;
try {
conn.setAutoCommit(false);
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int i = 0;
for (i = 0; i < 10000; i++) {
ps.setString(1, user.getUsername() + "-" + i);
ps.setString(2, user.getPassword() + "-" + i);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
id = rs.getLong(1);
System.out.println(">>>>>>>" + id);
}
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
user.setId(id);
return user;
}
private User SaveUser2(User user) {
String sql = "BEGIN insert into t_user(id,username,password) values(user_id.nextval,?,?) returning id into ?; END;";
Long id = -1L;
try {
conn.setAutoCommit(false);
CallableStatement cs = conn.prepareCall(sql);
for(int i=0;i<10000;i++){
cs.setString(1, user.getUsername() + "-" + i);
cs.setString(2, user.getPassword() + "-" + i);
cs.registerOutParameter(3, OracleTypes.NUMBER);
cs.execute();
id = cs.getLong(3);
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
user.setId(id);
return user;
}
public static void main(String[] args) {
JDBCDao dao = new JDBCDao();
Long start = System.currentTimeMillis();
User u = new User("andy", "andypwd");
dao.SaveUser2(u);
Long end = System.currentTimeMillis();
System.out.println(u.getId() + "--" + u.getUsername());
Long k = end - start;
System.out.println("消耗:" + k);
}
}
创新互联自2013年起,是专业互联网技术服务公司,拥有项目做网站、
网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元阿勒泰做网站,已为上家服务,为阿勒泰各地企业和个人服务,联系电话:18980820575
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享题目:jdbc:mysql和oracle插入一条数据返回主键-创新互联
文章网址:
http://shouzuofang.com/article/hespj.html