Springjdbc 简明教程

Spring JDBC - Configure Data Source

让我们在数据库 TEST 中创建数据库表 Student 。我假设您正在使用 MySQL 数据库,如果您使用任何其他数据库,则可以相应地更改 DDL 和 SQL 查询。

Let us create a database table Student in our database TEST. I assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly.

CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);

现在,我们需要向 JDBC 模板提供一个 DataSource,以便它能自我配置来获取数据库访问。您可以在 XML 文件中配置 DataSource,代码部分如下所示 −

Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code shown as follows −

<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
   <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
   <property name = "username" value = "root"/>
   <property name = "password" value = "admin"/>
</bean>

在下一章,我们将编写使用已配置数据库的第一个应用程序。

In the next chapter, we’ll write the first application using the database configured.