JdbcTemplateUtil公共類的使用-------java操作資料庫(2)
阿新 • • 發佈:2019-02-10
1.在xml配置JdbcTemplateUtil所需的資料來源
<!--2. 配置springDSN --> <bean id="springDSN" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/makefriends?useUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="123" /> </bean> <!-- 2. JdbcTemplate工具類例項 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false" lazy-init="false" autowire="default" > <property name="dataSource"> <ref bean="springDSN" /> </property> </bean>
2.編寫JdbcTemplateUtil公共類
package com.yun.utility; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class JdbcTemplateUtil { private static ApplicationContext ctx = new ClassPathXmlApplicationContext("config/sprhib-data.xml"); public static Object getBean(String beanName){ return ctx.getBean(beanName); } }
3.編寫測試類
<span style="font-size:18px;"><strong>package com.yun.test; import java.util.List; import java.util.Map; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import com.yun.model.User; import com.yun.utility.JdbcTemplateUtil; public class TestJdbcTemplate { /** * @param args */ @SuppressWarnings("unchecked") public static void main(String[] args) { // TODO Auto-generated method stub // DriverManagerDataSource ds=new DriverManagerDataSource(); // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/makefriends"); // ds.setUsername("root"); // ds.setPassword("123"); // JdbcTemplate jt=new JdbcTemplate(); // jt.setDataSource(ds); JdbcTemplate jt=(JdbcTemplate) JdbcTemplateUtil.getBean("jdbcTemplate"); //JdbcTemplate jt=new JdbcTemplate(); List<Map<String, Object>> list=jt.queryForList("select * from yunuser"); System.out.println(list.size()); for(int i=0;i<list.size();i++){ Map map=list.get(i); System.out.println(map); System.out.println(map.get("user_name")); } } } </strong></span>