//测试类
package druid; import util.JdbcUtilsDruid; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; public class druiddemo2 { public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; //1.获取连接 try { connection = JdbcUtilsDruid.getConnection(); String sql = "insert into stu values (?,?,?,?,?,?)"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,6); preparedStatement.setString(2,"嘿嘿嘿"); preparedStatement.setInt(3,44); preparedStatement.setDouble(4,88.8); preparedStatement.setDate(5, Date.valueOf("2018-01-01")); preparedStatement.setDate(6, Date.valueOf("2018-01-01")); int count = preparedStatement.executeUpdate(); System.out.println(count); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtilsDruid.close(preparedStatement,connection); } } }
连接池工具
package util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JdbcUtilsDruid { private static DataSource ds; static { Properties pro = new Properties(); try { pro.load(JdbcUtilsDruid.class.getClassLoader().getResourceAsStream("druid.properties")); ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return ds.getConnection(); } public static void close(Statement stmt,Connection conn){ close(null,stmt,conn); } public static void close(ResultSet rs,Statement stmt, Connection conn){ if (rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static DataSource getDataSource(){ return ds; } }
配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///db2 username=root password= initialSize=5 maxActive=10 maxWait=3000