#Spring JdbcTemplate入門@FDDLC

凡我出品,皆屬精品發表於2020-09-28

 pom.xml的內容:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>P031_HelloJdbcTemplate</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
    </dependencies>
</project>

 

Main.java的內容:

package cn.liuxingchang;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class Main {
    public static void main(String[] args) {
        //1、準備資料來源:這裡使用Spring內建的資料來源
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        //2、設定資料庫的相關屬性
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF8&serverTimezone=Asia/Shanghai";
        dataSource.setUrl(url);
        dataSource.setUsername("root");
        dataSource.setPassword("123456");

        //3、新建JdbcTemplate,並繫結資料來源
        JdbcTemplate template = new JdbcTemplate(dataSource);

        //4、進行CRUD操作
        template.execute("update account set money = 400 where id = 4");
    }
}

 

 

相關文章