使用JDBC连接数据库实际操作

JDBC,java data base connectivity,听名字就知道是用java连接数据库的,这里我就不多说啦QAQ~


一、准备工作

  1. 编写java程序的软件:IDEA
  2. 数据库:Mysql
  3. 数据库管理工具:Navicat

二、创建一张数据表

  1. 使用Navicat建表、插数据比较方便,也比较直观
    学生表
    一张简单的数据表就建好了,这是在test1数据库下的一张名叫student的数据表,表中只有简单的两个字段IDNAME,表示学生的学号和姓名,这两个字段的类型都是varchar(20),其中我将ID字段设置成了主键默认非空

  2. 使用Navicat可以直接设计表的结构,当然建表也可以是用DDL来建表
    student的DDL如下:

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `ID` varchar(20) NOT NULL DEFAULT '',
  `NAME` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DDL建立数据表
点击查询 –> 新建查询 –> 写入DDL代码 –> 点击运行 –> OK一张数据表建立成功!

三、编写java代码

编写java文件之前需要先导入Mysql驱动包,点击下载解压即可。

1. 连接数据库的工具类

package com.leechen.util;

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

/**
 * java连接数据库的工具类
 */
public class JdbcUtils {

    //连接数据库的各参数
    private static String url = "jdbc:mysql://127.0.0.1:3306/test1";
    private static String user = "root";
    private static String passworg = "Leec2018";

    /**
     * 静态注册驱动
     */
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver"); //Driver类的全限定名
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("注册驱动失败!! " + e);
        }
    }

    /**
     * 获取连接对象
     */
    public static Connection getConnection() {
        try {
            Connection conn = DriverManager.getConnection(url, user, passworg);
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 释放资源
     * 后打开的先关闭
     */
    public static void close(Connection conn, Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}

2. 实现增删查改的工具类

package com.leechen.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;


/**
 * 实现增删查改的工具类
 */
public class DbUtils {

    /**
     * 插入数据
     * @param tableName 表名
     * @param vaules 插入的值
     */
    public static void testInsert(String tableName, String vaules) {

        Connection conn = null;
        Statement stmt = null;

        try {
            //1.获取Connection对象
            conn = JdbcUtils.getConnection();
            //2.创建Statement对象
            stmt = conn.createStatement();
            //3.准备sql语句
            String sql = "INSERT INTO " + tableName + "VALUES('" + vaules + "')";
            //4.发送sql,执行sql语句
            stmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //5.关闭资源
            JdbcUtils.close(conn, stmt);
        }
    }

    /**
     * 删除数据
     * @param tableName 表名
     */
    public static void testDrop(String tableName) {

        Connection conn = null;
        Statement stmt = null;

        try {
            //1.获取Connection对象
            conn = JdbcUtils.getConnection();
            //2.创建Statement对象
            stmt = conn.createStatement();
            //3.准备sql语句
            String sql = "DELETE FROM " + tableName;
            //4.发送sql,执行sql语句,得到返回结果
            int count = stmt.executeUpdate(sql);
            //5.输出结果
            System.out.println("删除行为影响了" + count + "行数据!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //5.关闭资源
            JdbcUtils.close(conn, stmt);
        }
    }


    /**
     * 更改数据
     * @param tableName 表名
     * @param fieldName 字段名
     * @param condition 条件
     */
    public static void testUpdate(String tableName, String fieldName, String condition) {

        Connection conn = null;
        Statement stmt = null;

        try {
            //1.获取Connection对象
            conn = JdbcUtils.getConnection();
            //2.创建Statement对象
            stmt = conn.createStatement();
            //3.准备sql语句
            String sql = "UPDATE " + tableName + " SET " + fieldName + " WHERE " + condition;
            //4.发送sql,执行sql语句
            stmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //5.关闭资源
            JdbcUtils.close(conn, stmt);
        }
    }

    /**
     * 查询数据
     * @param tableName 表名
     */
    public static void testGetAll(String tableName) {

        Connection conn = null;
        Statement stmt = null;

        try {
            //1.获取Connection对象
            conn = JdbcUtils.getConnection();
            //2.创建Statement对象
            stmt = conn.createStatement();
            //3.准备sql语句
            String sql = "SELECT * FROM " + tableName;
            //4.发送sql,执行查询sql语句,返回查询结果
            ResultSet resultSet = stmt.executeQuery(sql);
            //5.输出查询结果
            while (resultSet.next()) {
                String column1 = resultSet.getString(1); //第一列的值
                String column2 = resultSet.getString(2); //第二列的值
                System.out.println(column1 + " " + column2);
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //5.关闭资源
            JdbcUtils.close(conn, stmt);
        }
    }
}

3. 实体类

package com.leechen.domain;

/**
 * 这是一个实体类,对应数据库里的student表
 */
public class Student {

    private String id; //对应字段ID
    private String name; //对应字段NAME

    //get和set方法
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //重写toString方法
    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

4. 测试

package com.leechen.test;

import com.leechen.domain.Student;
import com.leechen.util.DbUtils;

/**
 * 测试类
 */
public class JdbcTest {
    public static void main(String[] args) {

        String tableName = "`student`"; //表名
        Student student = new Student();
        student.setId("1");
        student.setName("张三");

        //删除已存在的数据
        DbUtils.testDrop(tableName);

        //插入一条数据
        System.out.println("\n" + student.toString() + "\n");
        DbUtils.testInsert(tableName, student.getId() + "','" + student.getName());
        DbUtils.testGetAll(tableName);
        System.out.println("插入一条数据成功!\n");

        //更改一条数据
        String fieldVaule = "`NAME`='李四'";
        String condition = "ID = '1'";
        DbUtils.testUpdate(tableName, fieldVaule, condition);
        DbUtils.testGetAll(tableName);
        System.out.println("更改一条数据成功!\n");
    }
}

四、测试结果

测试结果

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值