JDBC推荐连接
package study.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
public static Connection getConnection() throws Exception {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url,user,password);
return con;
}
public static void closeReduce(Connection con, Statement ps){
try {
if(ps!=null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeReduce(Connection con, Statement ps,ResultSet rs){
try {
if(ps!=null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

JDBC连接方式汇总
package study.transaction;
import org.junit.Test;
import study.util.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ConnectionTest {
@Test
public void testUpdate(){
String sql="update books set price=price+50 where id=?";
update(sql,27);
System.out.println("添加成功");
}
public int update(String sql,Object ...args) {
Connection con = null;
PreparedStatement ps = null;
try {
con = JDBCUtils.getConnection();
ps = con.prepareStatement(sql);
for(int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtils.closeReduce(con,ps);
}
return 0;
}
@Test
public void testUpadateWitTx() {
Connection con = null;
try {
con = JDBCUtils.getConnection();
con.setAutoCommit(false);
String sql="update books set price=price-50 where id=?";
update1(con,sql,27);
System.out.println("添加成功");
con.commit();
} catch (Exception e) {
e.printStackTrace();
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
JDBCUtils.closeReduce(con,null);
}
}
public int update1(Connection con,String sql,Object ...args) {
PreparedStatement ps = null;
try {
ps = con.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeReduce(null, ps);
}
return 0;
}
@Test
public void testGetConnectionTest() throws Exception {
Connection con =null;
con = JDBCUtils.getConnection();
System.out.println(con);
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}