java利用JDBC操作数据库

java用JDBC对数据库进行:‘增删改查’

首先创建创建数据库连接

这里我用的这是地址池自动连接

这里面是连接数据库的jar包,地址池的jar包
链接:https://pan.baidu.com/s/1Pd6mOl63oTvmMTFm4uMmhg 
提取码:4thw

第一个要创建一个属性文件夹,用料解决硬编码问题,以我的数据库为例

	db.properties文件夹:
	driverClassName=com.mysql.jdbc.Driver
	url=jdbc:mysql://127.0.0.1:3306/jdbc
	username=root
	password=123456

创建一个user类

package domain;

public class User {
    private String name;
    private int age;
    private int id;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id=" + id +
                '}';
    }

    public User(String name, int age, int id) {
        this.name = name;
        this.age = age;
        this.id = id;
    }

    public int getId() {
        return id;
    }

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

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

创建一个数据库增删改查的方法接口`

import domain.User;

import java.util.List;

public interface IUserdao {
//
    public void save(User user);

    public void update(User user);


    public void delete (int id);

    public User findOne(int id);

    public List<User> findAll();
    
}

创建一个实现类

package dao.impl;

import dao.IUserdao;
import domain.User;
import utils.JDBCutils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserImpl implements IUserdao {
    private PreparedStatement statement=null;
    public Connection conn=null;
    public ResultSet resultSet=null;
    //添加
    @Override
    public void save(User user) {
         conn = JDBCutils.instance.start();
        String sql="insert into user (name,age) values(?,?)";
        try {
            statement =conn.prepareStatement(sql);
            statement.setString(1,user.getName());
            statement.setInt(2,user.getAge());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JDBCutils.instance.close(conn,statement,null);
    }
//修改
    @Override
    public void update(User user) {
        conn = JDBCutils.instance.start();
        String sql="update user set name=?,age=? where id="+user.getId();
        try {
            statement =conn.prepareStatement(sql);
            statement.setString(1,user.getName());
            statement.setInt(2,user.getAge());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JDBCutils.instance.close(conn,statement,null);
    }

//删除
    @Override
    public void delete(int id) {
        conn = JDBCutils.instance.start();
        String sql="delete  from user where id="+id;
        try {
            statement =conn.prepareStatement(sql);
            statement.execute();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        JDBCutils.instance.close(conn,statement,null);
    }
    //查询单个
    public User findOne(int id){
        User user = new User();
        conn = JDBCutils.instance.start();
        String sql="select * from user where id="+id;
        try {
            statement =conn.prepareStatement(sql);

            statement.execute();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            resultSet = statement.getResultSet();
            while (resultSet.next()){
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JDBCutils.instance.close(conn,statement,resultSet);
    return  user;
    }
//查询所有
    @Override
    public List<User> findAll() {

        List<User> users = new ArrayList<>();
        conn = JDBCutils.instance.start();
        String sql="select * from user ";
        try {
            statement =conn.prepareStatement(sql);

            statement.execute();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            resultSet = statement.getResultSet();
            while (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JDBCutils.instance.close(conn,statement,resultSet);
        return  users;
    }

}

最后我们在创建一个Test类

package test.dao.impl; 

import dao.impl.UserImpl;
import domain.User;
import org.junit.Test;
import org.junit.Before; 
import org.junit.After;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

public class UserImplTest {
    UserImpl dao = new UserImpl();
@Test
public void testSave() throws Exception {
    User user1 = new User("钢铁侠", 19);
    dao.save(user1);
} 

@Test
public void testUpdate() throws Exception {
    User user1 = new User("超人", 19,4);
    dao.update(user1);
} 

@Test
public void testDelete() throws Exception { 
    dao.delete(5);
} 

@Test
public void testFindOne() throws Exception { 

    System.out.println( dao.findOne(1));
} 

@Test
public void testFindAll() throws Exception {
    List<User> all = dao.findAll();
    for (User u:all
         ) {
        System.out.println(u);
    }
}
} 

创建一个工具类

package utils;

import com.sun.org.apache.xerces.internal.util.PropertyState;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public enum JDBCutils {
    instance;
    private static Properties properties;
    private  static DataSource ds;
    static {
        properties=new Properties();
        try {
            //获取当前线程类构造器
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
            //利用地址池;连接到数据库
            ds= new BasicDataSourceFactory().createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //创建数据库的连接
    public Connection start(){

        try {
            return DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username"),properties.getProperty("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    return null;

    }
    //关流
    public void close(Connection conn, PreparedStatement statement,ResultSet resultSet){
        if (conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement!=null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(resultSet!=null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

这样我们就可以操作数据库了。

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值