Create a C3P0 Data Source
When creating a C3P0 data source, there are very few connections to the database using JDBC in actual development. Generally, the data source is used. C3P0 is an open source data source, and the actual project is used a lot:
1. Added support for maven.
c3p0
c3p0
0.9.1.2
2. Configure C3P0, the default configuration file c3p0-config.xml:
root
jdbc:mysql://localhost:3306/charts
com.mysql.jdbc.Driver
root
5
5
5
10
25
5
3. Reference a data source
Package com. hexun. utils; import java. SQL. connection; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import javax. SQL. dataSource; import com. mchange. v2.c3p0. comboPooledDataSource;/*** JDBC tool class ** contains methods such as getting database connections and disabling database resources. */public class JDBCTools {// process database transactions // submit the public static void commit (Connection connection) {if (connection! = Null) {try {connection. commit ();} catch (SQLException e) {e. printStackTrace () ;}}// rollback transaction public static void rollback (Connection connection) {if (connection! = Null) {try {connection. rollback ();} catch (SQLException e) {e. printStackTrace () ;}}// start the transaction public static void beginTx (Connection connection) {if (connection! = Null) {try {connection. setAutoCommit (false);} catch (SQLException e) {e. printStackTrace () ;}} private static DataSource dataSource = null; // The database connection pool should be initialized only once. static {dataSource = new ComboPooledDataSource ("c3p0");} public static Connection getConnection () throws Exception {return dataSource. getConnection ();} public static void releaseDB (ResultSet resultSet, Statement statement, Connection connection) {if (ResultSet! = Null) {try {resultSet. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (statement! = Null) {try {statement. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (connection! = Null) {try {// when the Connection object of the database Connection pool is closed, // The database Connection is returned to the database Connection pool instead of being closed. connection. close ();} catch (SQLException e) {e. printStackTrace ();}}}}
You can directly call Static Methods When referencing them.