Java JDBC 入门

package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/*
* JDBC快速入门
*
* */
public class JDBCDemo1 {

    public static void main(String[] args) throws  Exception {
        //1、 导入驱动jar包  ,  导入mysql驱动java包
        // mysql java包下载地址 https://dev.mysql.com/downloads/connector/j/
        // 在项目中建立libs文件夹,把  mysql-connector-java-8.0.22.jar 复制到libs文件夹下,
        // 然后对libs右键 Add as library,真正的把jar包加入项目
        //2、 注册驱动
        // 8.0版本 com.mysql.cj.jdbc.Driver    ,5.0版本 com.mysql.jdbc.Driver
        // jdk版本需要1.8以上
        Class.forName("com.mysql.cj.jdbc.Driver"); //把类加载进内存
        //3、  获取数据库连接对象
                    //8.0版本后面要加?serverTimezone=UTC
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC", "root", "password");
        //4、定义sql语句
        String sql="update account set balance =500 where id=1";
        //5、获取sql执行对象 Statement
        Statement stmt = conn.createStatement();
        //6、执行sql
        int count= stmt.executeUpdate(sql);
        //7、处理结果
        System.out.println(count);
        //8、释放资源
        stmt.close();

    }


}

 

 

//-------------------------------------------------------------

使用maven创建的工程

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>com.tuy</groupId>
    <artifactId>spring_jdbc</artifactId>
    <version>1.0-SNAPSHOT</version>



    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>


        <!--        spring集成junit需要的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>untitled</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->


            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                    <configuration>
                        <skipTests>true</skipTests>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>

                <!--可以在Setting-Livetemplate 把下面添加成模板-->
                <plugin>

                    <!--jdk插件-->
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>utf-8</encoding>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>


</project>

 jdbc.properties文件,放在resources目录下

jdbc.drive=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useSSL=false&characterEncoding=utf8
jdbc.username=root
jdbc.passwrod=root

applicationContext.xml 文件,放在resources目录下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置数据源对象    -->
    <!--加载外部的配置文件 jdbc.properties-->
    <!--需要引入命名空间  xmlns:context="http://www.springframework.org/schema/context"  -->
    <!--需要引入命名空间   http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--    配置druid数据源  -->
<!--  com.alibaba.druid.pool.DruidDataSource  -->
<!--    注意 c3po和driud的属性不一样-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置属性,需要set方法后面的名字  , 值 通过外部配置文件获取      -->
        <property name="driverClass" value="${jdbc.drive}" ></property>
        <property name="jdbcUrl" value="${jdbc.url}" ></property>
        <property name="user" value="${jdbc.username}" ></property>
        <property name="password" value="${jdbc.passwrod}" ></property>
    </bean>

    <!--配置jdbc模板对象    -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入数据源对象        -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
</beans>

//测试文件1

package com.tuy.test;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.beans.PropertyVetoException;
import java.sql.SQLException;

public class JdbcTemplateTest {


    @Test
//  测试spring产生 jdbcTenmplate对象
    public  void test2()
    {
        ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate=app.getBean(JdbcTemplate.class);
        int rows = jdbcTemplate.update("insert into account value (?,?)", "zhangsan", 2000);
        System.out.println(rows);
    }


    @Test
    //测试JdbcTemplate 开发
    public void test1() throws PropertyVetoException, SQLException {
        //创建数据源对象
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useSSL=false");
        dataSource.setUser("root");
        dataSource.setPassword("root"); // 注意密码不一样


        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);  //设置数据源对象,知道数据在哪里
        //执行操作
        int rows = jdbcTemplate.update("insert into account value (?,?)", "tom", 5000);
        System.out.println(rows);

    }

}

//测试文件2

package com.tuy.test;


import com.tuy.test.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)             //用springJunit来测试
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //修改(更新)
    @Test
    public void testUpdate(){
        jdbcTemplate.update("update account set money=? where name=?",10000,"tom");
    }

    //删除
    @Test
    public void testDelete(){
        jdbcTemplate.update("delete from account where name=?","tom");
    }

    //查询所有
    @Test
    public void testQueryAll(){

        //第二个参数是一个 RowMapper类型, 一个接口
        //BeanPropertyRowMapper 是 RowMapper的实体实现类
        //注意Account内的属性要跟数据库内的字段一致
        List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        System.out.println(accountList);
    }

    //查询一个对象
    @Test
    public void testQueryOne(){
        Account account = jdbcTemplate.queryForObject("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), "tom");
        System.out.println(account);
    }

    //查询总数
    //查询一个简单的数据类型
    @Test
    public void testQueryCount(){
        Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
        System.out.println(count);
    }

}

// CTr+Alt+B 查看接口的实现类

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值