package com.wei.db;
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 java.util.List;
public class DBHelper {
String sDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String sDBUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=Test";
String sUser = "sa";
String sPwd = "123456";
private Connection conn = null;
public boolean connect() {
try {
Class.forName(sDriverName);
try {
conn = DriverManager.getConnection(sDBUrl, sUser, sPwd);
return true;
} catch (SQLException e) {
System.out.println("DBConnect:"+e);
return false;
}
} catch (ClassNotFoundException e) {
System.out.println("connect:"+e);
return false;
}
}
public void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("close:"+e);
}
}
}
public boolean executeMore(List<String> sqlList) {
if (conn!=null) {
try {
boolean isAutoCommit=conn.getAutoCommit();
conn.setAutoCommit(false);
Statement statement= conn.createStatement();
for (int i = 0; i < sqlList.size(); i++) {
statement.addBatch(sqlList.get(i));
}
statement.executeBatch();
conn.commit();
conn.setAutoCommit(isAutoCommit);
} catch (Exception e) {
System.out.println("executeMore:"+e);
try {
conn.rollback();
} catch (Exception rollbackError) {
System.out.println("rollback:"+e);
}
return false;
}
}
return false;
}
public boolean execute(String sql) {
if (conn!=null) {
try {
PreparedStatement pst=conn.prepareStatement(sql);
pst.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println("execute:"+e);
return false;
}
}
return false;
}
public ResultSet query(String sql){
try {
Statement statement= conn.createStatement();
ResultSet rs=statement.executeQuery(sql);
return rs;
} catch (Exception e) {
System.out.println("query:"+e);
return null;
}
}
}
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.wei.db.DBHelper;
public class Test {
public static void main(String[] args) {
boolean res=false;
List<String> sqlList=new ArrayList<String>();
for (int i = 1; i < 50; i++) {
String sql="insert into UserInfo(user_name) values('number"+i+"')";
sqlList.add(sql);
}
DBHelper helper=new DBHelper();
res=helper.connect();
if (res) {
System.out.println("Connect success...");
helper.executeMore(sqlList);
ResultSet rs=helper.query("select * from UserInfo");
try {
while (rs.next()) {
String name=rs.getString(1);
System.out.println(name);
}
} catch (Exception e) {
System.out.println("ResultSet:"+e);
}
}else {
System.out.println("Connect fail...");
}
helper.close();
}
}