Java中连接数据库
第一种方式:
public class DBHelper { public static final String url = "jdbc:mysql://127.0.0.1/estoresystem"; public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; public static final String password = "admin"; public Connection conn = null; public PreparedStatement pst = null; public DBHelper(String sql) { try { Class.forName(name);//指定连接类型 conn = DriverManager.getConnection(url, user, password);//获取连接 pst = conn.prepareStatement(sql);//准备执行语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.conn.close(); this.pst.close(); } catch (SQLException e) { e.printStackTrace(); } } }
第二种方式:
import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; import java.sql.Connection; import java.sql.SQLException; public class DataSourceUtils { /*** * 连接数据库 */ private static DataSource dataSource = new ComboPooledDataSource(); private static ThreadLocal<Connection> tl = new ThreadLocal<>(); public static DataSource getDataSource(){ return dataSource; } /*** * 当DBUtuls需要手动控制事务的时,调用该方法获得一个连接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { Connection con = tl.get(); if(con == null){ con = dataSource.getConnection(); } return con; } //设置事务为手动事务,相当于开启事务 public static void startTransaction() { try { getConnection().setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } //设置事务回滚 public static void rollback(){ try { getConnection().rollback(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //事务提交 public static void commitAndReleased(){ try { getConnection().commit(); getConnection().close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } tl.remove(); } }

浙公网安备 33010602011771号