Spring学习日记(3)

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&amp;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

运行结果:

 如果运行结果是绿色的 就是运行成功,反之,就需要去解决错误信息再次运行

 可以看到,数据表创建成功。

Spring Web开发创建MySQL8数据库表 完成!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值