1. 程式人生 > >使用spring的JdbcTemplate操作資料庫

使用spring的JdbcTemplate操作資料庫

場景: 使用spring的JdbcTemplate操作資料庫
1.建表語句,本例是Mysql資料庫

CREATE TABLE `t_city` (
  `CITY_NAME` VARCHAR(64) COLLATE utf8_bin NOT NULL COMMENT '城市名',
  `LAND_AREA` DOUBLE DEFAULT NULL COMMENT '城市面積',
  `POPULATION` BIGINT(16) DEFAULT NULL COMMENT '城市人口',
  `GROSS` DOUBLE DEFAULT NULL COMMENT '生產總值',
  `AREA_NUMBER` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '行政區劃程式碼',
  `POSTAL_CODE` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '郵政編碼',
  `TELEPHONE_CODE` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '電話區號',
  `CAR_CODE` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '車牌程式碼',
  `CITY_DESCRIBE` VARCHAR(512) COLLATE utf8_bin DEFAULT NULL COMMENT '城市描述'
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='城市資訊表'

2.配置資料來源和獲取JdbcTemplate

/**資料庫連線需要字串*/
	public static final String username = "root";
	public static final String password = "123456";
	public static final String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/zbzdb";
	public static final String driverName = "com.mysql.jdbc.Driver";
	
	public static JdbcTemplate jdbcTemplate = getJdbcTemplate();
	
	/**獲取一個JdbcTemplate例項物件*/
	public static JdbcTemplate getJdbcTemplate() {
		
		DruidDataSource dataSource = new DruidDataSource();
		// 設定資料來源屬性引數
		dataSource.setPassword(password);
		dataSource.setUrl(jdbcUrl);
		dataSource.setUsername(username);
		dataSource.setDriverClassName(driverName);
		// 獲取spring的JdbcTemplate
		JdbcTemplate jdbcTemplate = new JdbcTemplate();
		// 設定資料來源
		jdbcTemplate.setDataSource(dataSource);
		return jdbcTemplate;
	}

3.查詢相關方法

    /**1.使用 queryForList(String sql)*/
	public static List<Map<String, Object>> queryForList(){
		
		/**1.組裝sql*/
		String sql = "SELECT CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER FROM t_city ";
		/**.呼叫queryForList*/
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
		return result;
	}
	/**2.使用 queryForList(String sql, Object... args)*/
	public static List<Map<String, Object>> queryForList(String cityName, String areaNember){
		
		/**1.組裝sql*/
		String sql = "SELECT CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER FROM t_city WHERE CITY_NAME= ? AND AREA_NUMBER= ? ";
		/**2.陣列型別引數*/
		Object[] params = new Object[] { cityName, areaNember };
		/**3.呼叫queryForList*/
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, params);
		return result;
	}
	
	/**3.使用 queryForList(String sql, Object... args)*/
	public static List<Map<String, Object>> queryForList2(String cityName, String areaNember){
		
		/**1.組裝sql*/
		String sql = "SELECT CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER FROM t_city WHERE CITY_NAME= ? AND AREA_NUMBER= ? ";
		/**2.呼叫queryForList*/
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, cityName,areaNember);
		return result;
	}

4.插入相關方法

    /**4.插入一條記錄*/
	public static void insert(){
		/**1.組裝sql*/
		String sql = "INSERT INTO  t_city (CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER ) VALUE('泉州',11014.78, 865, 7548.01, '350500' ) ";
		/**2.呼叫update*/
		jdbcTemplate.update(sql);
	}
	
	/**5.插入一條記錄,帶引數*/
	public static void insertParam(String cityName,String areaNumber){
		/**1.組裝sql*/
		String sql = "INSERT INTO  t_city (CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER ) VALUE(?, ?, ?, ?, ? )  ";
		
		Object[] params = new Object[] {
				cityName,
				11014.78,
				865,
				7548.01,
				areaNumber
		};
		/**2.呼叫update*/
		jdbcTemplate.update(sql,params);
	}

5.更新相關方法

    /**6.更新使用set語句*/
	public static int updateData(String cityName,String cityDesc,String carCode){
		String sql = "UPDATE t_city SET CITY_DESCRIBE = ?,CAR_CODE = ?  WHERE CITY_NAME=? ";
		jdbcTemplate.update(sql, cityDesc,carCode,cityName);
		return 1;
	}

6.刪除相關方法

    /**7.刪除一條記錄*/
	public static void delete(){
		/**1.組裝sql*/
		String sql = "delete from t_city where CITY_NAME='泉州' ";
		/**2.呼叫update*/
		jdbcTemplate.update(sql);
	}
	
	/**8.帶引數刪除*/
	public static void delete(String cityName){
		/**1.組裝sql*/
		String sql = "delete from t_city where CITY_NAME= ? ";
		/**2.呼叫update*/
		jdbcTemplate.update(sql,cityName);
	}

7.批量插入相關方法

/**9.批量插入*/
	public static int[]insertBatch(final List<Map<String, Object>> list){
		/**1.組裝sql*/
		String sql = " INSERT INTO t_city  "
				     +"  (CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER,POSTAL_CODE,TELEPHONE_CODE,CAR_CODE,CITY_DESCRIBE) "
				     + "  VALUE(?, ?, ?, ?, ? ,? , ?, ?, ?) ";
		/**2.組裝sql*/
		int[] result =  jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){
			
			@Override
			public int getBatchSize() {
				return list.size();
			}

			@Override
			public void setValues(PreparedStatement ps, int i)
					throws SQLException {
				try {
					Map<String, Object> map = list.get(i);
					ps.setObject(1, map.get("CITY_NAME"));
					ps.setObject(2, map.get("LAND_AREA"));
					ps.setObject(3, map.get("POPULATION"));
					ps.setObject(4, map.get("GROSS"));
					ps.setObject(5, map.get("AREA_NUMBER"));
					ps.setObject(6, map.get("POSTAL_CODE"));
					ps.setObject(7, map.get("TELEPHONE_CODE"));
					ps.setObject(8, map.get("CAR_CODE"));
					ps.setObject(9, map.get("CITY_DESCRIBE"));
				} catch (SQLException e) {
					e.printStackTrace();
					throw e;
				}
			}
		});		
		return result;
	}

8.測試main函式

public class TestJdbcTemplate {
	
	public static void main(String [] args){
		
		System.out.println("測試開始......");
		List<Map<String, Object>> tt1 = OperateJdbcTemplateUtils.queryForList();
		List<Map<String, Object>> tt2 = OperateJdbcTemplateUtils.queryForList("廈門","350200");
		System.out.println(tt2.toString());
        OperateJdbcTemplateUtils.insertParam("泉州", "350500");
		OperateJdbcTemplateUtils.updateData("泉州","鞋都","閩C");
        //OperateJdbcTemplateUtils.delete();
        //OperateJdbcTemplateUtils.delete("泉州");
		System.out.println("測試結束......");
	}
}

9.完整類

public class OperateJdbcTemplateUtils {
	
	/**資料庫連線需要字串*/
	public static final String username = "root";
	public static final String password = "123456";
	public static final String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/zbzdb";
	public static final String driverName = "com.mysql.jdbc.Driver";
	
	public static JdbcTemplate jdbcTemplate = getJdbcTemplate();
	
	/**獲取一個JdbcTemplate例項物件*/
	public static JdbcTemplate getJdbcTemplate() {
		
		DruidDataSource dataSource = new DruidDataSource();
		// 設定資料來源屬性引數
		dataSource.setPassword(password);
		dataSource.setUrl(jdbcUrl);
		dataSource.setUsername(username);
		dataSource.setDriverClassName(driverName);
		// 獲取spring的JdbcTemplate
		JdbcTemplate jdbcTemplate = new JdbcTemplate();
		// 設定資料來源
		jdbcTemplate.setDataSource(dataSource);
		return jdbcTemplate;
	}
	
	/**1.使用 queryForList(String sql)*/
	public static List<Map<String, Object>> queryForList(){
		
		/**1.組裝sql*/
		String sql = "SELECT CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER FROM t_city ";
		/**.呼叫queryForList*/
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
		return result;
	}
	/**2.使用 queryForList(String sql, Object... args)*/
	public static List<Map<String, Object>> queryForList(String cityName, String areaNember){
		
		/**1.組裝sql*/
		String sql = "SELECT CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER FROM t_city WHERE CITY_NAME= ? AND AREA_NUMBER= ? ";
		/**2.陣列型別引數*/
		Object[] params = new Object[] { cityName, areaNember };
		/**3.呼叫queryForList*/
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, params);
		return result;
	}
	
	/**3.使用 queryForList(String sql, Object... args)*/
	public static List<Map<String, Object>> queryForList2(String cityName, String areaNember){
		
		/**1.組裝sql*/
		String sql = "SELECT CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER FROM t_city WHERE CITY_NAME= ? AND AREA_NUMBER= ? ";
		/**2.呼叫queryForList*/
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, cityName,areaNember);
		return result;
	}
	
	/**4.插入一條記錄*/
	public static void insert(){
		/**1.組裝sql*/
		String sql = "INSERT INTO  t_city (CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER ) VALUE('泉州',11014.78, 865, 7548.01, '350500' ) ";
		/**2.呼叫update*/
		jdbcTemplate.update(sql);
	}
	
	/**5.插入一條記錄,帶引數*/
	public static void insertParam(String cityName,String areaNumber){
		/**1.組裝sql*/
		String sql = "INSERT INTO  t_city (CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER ) VALUE(?, ?, ?, ?, ? )  ";
		
		Object[] params = new Object[] {
				cityName,
				11014.78,
				865,
				7548.01,
				areaNumber
		};
		/**2.呼叫update*/
		jdbcTemplate.update(sql,params);
	}
	/**6.更新使用set語句*/
	public static int updateData(String cityName,String cityDesc,String carCode){
		String sql = "UPDATE t_city SET CITY_DESCRIBE = ?,CAR_CODE = ?  WHERE CITY_NAME=? ";
		jdbcTemplate.update(sql, cityDesc,carCode,cityName);
		return 1;
	}
	/**7.刪除一條記錄*/
	public static void delete(){
		/**1.組裝sql*/
		String sql = "delete from t_city where CITY_NAME='泉州' ";
		/**2.呼叫update*/
		jdbcTemplate.update(sql);
	}
	
	/**8.帶引數刪除*/
	public static void delete(String cityName){
		/**1.組裝sql*/
		String sql = "delete from t_city where CITY_NAME= ? ";
		/**2.呼叫update*/
		jdbcTemplate.update(sql,cityName);
	}
	
	
	
	/**9.批量插入*/
	public static int[]insertBatch(final List<Map<String, Object>> list){
		/**1.組裝sql*/
		String sql = " INSERT INTO t_city  "
				     +"  (CITY_NAME,LAND_AREA,POPULATION,GROSS,AREA_NUMBER,POSTAL_CODE,TELEPHONE_CODE,CAR_CODE,CITY_DESCRIBE) "
				     + "  VALUE(?, ?, ?, ?, ? ,? , ?, ?, ?) ";
		/**2.組裝sql*/
		int[] result =  jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){
			
			@Override
			public int getBatchSize() {
				return list.size();
			}

			@Override
			public void setValues(PreparedStatement ps, int i)
					throws SQLException {
				try {
					Map<String, Object> map = list.get(i);
					ps.setObject(1, map.get("CITY_NAME"));
					ps.setObject(2, map.get("LAND_AREA"));
					ps.setObject(3, map.get("POPULATION"));
					ps.setObject(4, map.get("GROSS"));
					ps.setObject(5, map.get("AREA_NUMBER"));
					ps.setObject(6, map.get("POSTAL_CODE"));
					ps.setObject(7, map.get("TELEPHONE_CODE"));
					ps.setObject(8, map.get("CAR_CODE"));
					ps.setObject(9, map.get("CITY_DESCRIBE"));
				} catch (SQLException e) {
					e.printStackTrace();
					throw e;
				}
			}
		});		
		return result;
	}
	
}


以上,TKS.