目录
一、目录结构
二、定义一个XML,名为:applicationContext.xml。位置放在了src下面。
二、编写测试类,名为:JdbcTemplateTest
三、其他情况
一、目录结构
二、定义一个XML,名为:applicationContext.xml。位置放在了src下面。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 数据库驱动-->
<!-- property都是通过setter赋值,后面的是要设置的参数-->
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<!-- 连接数据库的url 特别提醒:jdbc:mysql//服务器地址/数据库名-->
<!-- value="jdbc:mysql://localhost/db1" 这个db1要改成你的数据库库名。-->
<property name="url" value="jdbc:mysql://localhost/db1"></property>
<!-- 连接数据库的用户名-->
<property name="username" value="root"></property>
<!-- 连接数据库的密码-->
<property name="password" value="123456"></property>
</bean>
<!-- 配置JDBC模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源。-->
<!-- ref引用上一个bean的对象。-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
二、编写测试类,名为:JdbcTemplateTest
package com.stx.chapter04.jdbc;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateTest {
/*public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jt =(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
jt.execute("CREATE table message(id int PRIMARY KEY,name CHAR(20),sex CHAR(4),dress CHAR(80))");
System.out.println("信息表message创建成功!");
}*/
// 这是导入的单元测试。Junit4开源框架。
@Test
public void mainTest(){/*
特别提醒,如果是放在src下面的其他包,需要将其整个包名暴露出来。
例如 String XmlPath = "com\stx\chapter04\jdbc\applicationContext.xml";
在传递给ClassPathXmlApplicationContext(XmlPath);
*/
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jt =(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
jt.execute("CREATE table message(id int PRIMARY KEY,name CHAR(20),sex CHAR(4),dress CHAR(80))");
System.out.println("信息表message创建成功!");
}
}
三、其他情况
(一)第一个报错。是我自己的数据库名称不对。
第二个报错:该表已经存在了。
(二)运行结果