日期:2014-05-16  浏览次数:20503 次

使用JDBC及基于Spring的JDBC连接数据库
早上写了两段代码,一个是使用jdk中的JDBC连接数据库,代码如下:
Class.forName("com.mysql.jdbc.Driver").newInstance();
			Connection con=java.sql.DriverManager.getConnection("jdbc:mysql://localhost/books?useUnicode=true&characterEncoding=GBK","root","weishenme2");
			   Statement stmt=con.createStatement();
			    ResultSet rst=stmt.executeQuery("select * from book");
			    while(rst.next())
			    {
			        System.out.println(rst.getString("bookId"));
			        System.out.println(rst.getString("bookName"));
			        System.out.println(rst.getString("publisher"));
			        System.out.println("price");
			    }


后来又使用了基于Spring连接数据库,在spring.xml文件中声明如下bean:
<bean id="ds"    
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>  
		<property name="url" value="jdbc:mysql://localhost:3306/young"/>  
		<property name="username" value="root"/>  
		<property name="password" value="weishenme2"/>  
	</bean>

这样在程序中就可以直接使用它来创建Connection:
final ArrayList<User> users=new ArrayList<User>();
		Resource resource = new ClassPathResource("dao/jdbc/spring.xml");
		BeanFactory factory = new XmlBeanFactory(resource);
		DriverManagerDataSource ds=(DriverManagerDataSource) factory.getBean("ds");
		JdbcTemplate jt=new JdbcTemplate(ds);
		jt.query("SELECT * FROM user", new RowCallbackHandler(){

			public void processRow(ResultSet rs) throws SQLException {
					User user=new User();
					user.setId(rs.getInt("id"));
					user.setUsername(rs.getString("username"));
					user.setPassword(rs.getString("password"));
					user.setEmail(rs.getString("email"));
					users.add(user);
			}
			
		});

下一步就是要使用SpringDM连接,会在稍后的文章中讲述。