Environment:
Java SE 1.5
Spring-2.5.1
Mysql-connector-java-5.1.5.zip
Mysql 5.x
To get the data from the database, we first need to get a database connection. Spring completes this work by DataSource objects. DataSource is part of the JDBC specification and is considered a common database connection factory. By using DataSource, the container or framework can separate the details of the connection pool and transaction management from the application code. As a developer, you may need to know the details of connecting to a database as you develop and test your product. But you don't need to know the details when the product is implemented. Typically, your database administrator will help you set up your data source.
When using spring JDBC, you can either get the data source through Jndi or configure the data source yourself (using the DataSource implementation class provided by spring). Use the latter to make unit tests easier to detach from the Web container. Here we will use Drivermanagerdatasource, but DataSource has a variety of implementations, which we'll talk about later. Using Drivermanagerdatasource is no different from the way you used to get a JDBC connection. You must first specify the fully qualified name of the JDBC driver so that DriverManager can load the JDBC driver class, and then you must provide a URL (depending on JDBC driver, please refer to the relevant JDBC-driven documentation for the correct settings), Finally you must provide a user name and password to connect to the database.
The two paragraphs above are excerpted from the original spring development document, and I write a small application to test the effect of srping JDBC support.
The next test is to achieve a goal: to query the MySQL database testdb a table t_user data by fetching the spring's data source.
First, create the project, loader use the toolkit and driver. and add spring's profile Applicationcontext.xml to the source code directory, and the configuration reads as follows:
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!--数据库的数据源定义-->
<bean id="rptds" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/testdb</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>leizhimin</value>
</property>
</bean>
</beans>