Spring Web开发创建MySQL8数据库表
本次的操作相较前两次,属实是容易了不少,报错点相当少。
Junit相关包链接:https://pan.quark.cn/s/ee7878b6519a
本次会用到Junit测试
1,创建动态网页项目,根据实际情况配置tomcat(没有的可以点击Download and Install),把jar包复制到webapp(可能有的不是这个名称,创建项目自定义的名称)下的WEB-INF下的lib包内
不需要手动添加到环境
2,在src下新建一个名为sofrware.demo的包,包里新建一个名为test的包,在此过程中顺便在src下新建一个Spring Bean Configuration File的xml文件
这次只需要选中beans(不选的话可能也会默认选择)
编写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.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver "></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/spring2022?userUnicode=true&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="liu19780928"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
值得注意的是其中的bean的参数不要写错,根据自己的实际情况填写。(如果是5.0的mysql,在driveClassName的值里就是com.mysql.jdbc.Driver),url参数里的3306后是本次的数据库名称 spring2022
第二个bean里的id jdbcTemplate待会会在测试类中出现。
3,在software.demo.test包下创建我们这次的测试类TestDemo.java
package software.demo.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestDemo {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testCreate() {
String sql = "create table account(id int ,uname varchar(20) not null,balance double not null)";
jdbcTemplate.execute(sql);
}
}
注意Test包不要导错,是org.junit.Test
4,打开数据库创建新数据库spring2022
mysql> create database spring2022;
Query OK, 1 row affected (0.01 sec)
mysql>
5,运行测试类,右键选中Run As→JUnit Test
运行结果:
如果运行结果是绿色的 就是运行成功,反之,就需要去解决错误信息再次运行
可以看到,数据表创建成功。