1. 程式人生 > >JDBC 使用和配置

JDBC 使用和配置

工具類 logs font etc es2017 data mysq try url

/**
 * 數據庫工具類,封裝數據庫操作中多次使用的數據庫操作代碼
 * @author Administrator
 *
 */
public class DBUtils {
	
	public static Connection getConnection() {

		Connection connection = null;
		try {

			Class.forName("com.mysql.jdbc.Driver");

			String databaseName = "jdbc_test";
			String url = "jdbc:mysql://localhost:3306/" + databaseName;
			String user = "root";
			String password = "111";

			connection = DriverManager.getConnection(url, user, password);

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;

	}

}

*Connection connection = DBUtils.getConnection(); 

*PreparedStatement preparedStatement = connection.prepareStatement(sql);

*ResultSet resultSet = preparedStatement.executeQuery();

以上三個流都需要進行關閉 也都可以用try - with - resource 進行關閉 (自動關閉 不需要手動)

技術分享

JDBC 使用和配置