springBoot整合JDBC

在springboot项目中利用jdbc插入sql语句

 

package com.zy.pj.sys.dao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.*;

/*通过此单元测试类获取数据源对象
*@SpringBootTest 注解描述的类为springboot中的单元测试类
* 说明
* 1、springboot中的单元测试类必须放在启动类所在包或子包
* 2、springboot中单元测试类必须使用springbootTest注解描述*/
@SpringBootTest
public class DataSourceTests {
    /*在项目中添加了数据库相关依赖,springboot底层会自动帮助我们配置一个数据源
    * @Autowired注解描述属性时,是高数spring容器,要基于反射机制为属性赋值(依赖注入)*/
    @Autowired
    private DataSource dataSource;
    @Test
    void testgetConnection() throws SQLException {
        //获取连接时,会基于datasource获取到连接池对象,从而从池中获取连接
        Connection connection = dataSource.getConnection();
        System.out.println("con="+connection);
    }
    @Test
    void TestSaveNotice() throws SQLException, ClassNotFoundException { //通过此方法基于jdbc向数据库写入一条数据
        //创建连接
        Connection conn = dataSource.getConnection();
        //创建statement (sql传送器  ==》负责与将sql发生到数据端)
        String sql="insert into sys_notice(title,content,type,status,createdTime,createdUser,modifiedTime,modifiedUser)"+
                            "Value('结课通知','2021/4/16 4月','1','0',now(),'tony',now(),'tony')";
        Statement statement =conn.prepareStatement(sql);
        //发送sql
        boolean flag = statement.execute(sql);
        //处理结果
        if (flag){
            System.out.println("insert ok");
        }
        //释放资源
        statement.close();
        conn.close();
    }
    
     @Test
    void TestSaveNotice01() throws SQLException, ClassNotFoundException { //通过此方法基于jdbc向数据库写入一条数据
        //创建连接
        Connection con = dataSource.getConnection();
        //创建statement (sql传送器  ==》负责与将sql发生到数据端)
        String sql="insert into             sys_notice(title,content,type,status,createdTime,createdUser,modifiedTime,modifiedUser)"+
                "Value(?,?,?,?,?,?,?,?)"; //?表示占位符
        PreparedStatement st =con.prepareStatement(sql); //预编译方式创建statement
        //发送sql
       st.setString(1, "论文通知");
       st.setString(2, "通知");
       st.setString(3, "1");
       st.setString(4, "0");
       st.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
       st.setString(6, "json");
       st.setTimestamp(7, new Timestamp(System.currentTimeMillis()));
       st.setString(8, "tony");
       st.execute();

        //处理结果
        //释放资源
        st.close();
        con.close();

        }



}

了解更详细的代码,请点击:https://gitee.com/zhaoyuanq994/code

posted @ 2021-04-17 16:27  年华只余一地悲凉  阅读(98)  评论(0编辑  收藏  举报
/*粒子线条,鼠标移动会以鼠标为中心吸附的特效*/