The way of learning jdbc (3)

There are several problems

1) The existence of hard coding (username and password, url and classnameDriver) will be changed at any time

2) Just load the class file once, and load the file every time

3) The connection object needs to be created every time it queries, which is a waste of resources

4) Close resource code is long and has no technical content (dry principle 44)

5) Splicing sql statements is disgusting

Solution ()

1) Storing username and password with configuration file(

Create the resource folder in the project, and then create the db.properties file to store the datasourse configuration information of the project)

2) Create the package util in the project, and then create the Jdbcutil class (that is, the jdbc tool class)

Load bytecode in static code

3) Create the method getconn () in the Jdbcutil class to get the connection object and use the druid database connection pool

4) Create the method close() in the Jdbcutil class to close the resource

5) Replace statement with preparestatement

package util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

public class Jdbcutil {
	public static DataSource ds=null;
	static {
		try {
			Properties p=new Properties();
			InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
			p.load(in);
			Class.forName(p.getProperty("driverClassName"));
			ds=DruidDataSourceFactory.createDataSource(p);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	public  static Connection getconn() throws SQLException {
		return ds.getConnection();
	}
	public static  void close(Connection conn,Statement sta,ResultSet rs) {
		// TODO Auto-generated method stub
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				if (sta != null) {
					sta.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}finally {
				try {
					if (conn != null) {
						conn.close();
					}
				} catch (Exception e3) {
					// TODO: handle exception
				}
			}
		}
	}
}

 

Tags: SQL Java Druid JDBC

Posted on Sun, 05 Jan 2020 21:41:27 -0800 by badboy1245