使用execute方法建一张用户表,execute()方法里可以执行SQL语句.
JdbcTemplateTest.java:
package com.liu.jdbc;
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 jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
jdbcTemplate.execute("create table user(id int primary key auto_increment,username varchar(20))");
System.out.println("user表创建成功");
}
}
ApplicationContext.xml配置文件:
<?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-4.3.xsd">
<!-- 配置数据源 -->
<bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 数据库驱动 -->
<property name="driverClassName" value = "com.mysql.jdbc.Driver"></property>
<!-- 数据库url -->
<property name="url" value = "jdbc:mysql://localhost:3306/test"></property>
<!-- 数据库用户名 -->
<property name="username" value = "root"></property>
<!-- 数据库密码 -->
<property name="password" value = "root"></property>
</bean>
<!-- 配置jdbc模板类 -->
<bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源 -->
<property name="dataSource" ref = "dataSource"></property>
</bean>
</beans>
需要的包: