JDBCUtils工具类——statement,非配置文件版实现CRUD

package test;

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

import org.junit.Test;

import util.JDBCUtils;

/**
 * 这个类用来测试JDBC工具类
 */
public class UtilsTest {
    //查询account表里的所有数据
    @Test
    public void queryUser(){
        Connection conn=null;
        Statement st=null;
        ResultSet rs=null;
        try {
            //注册驱动 ,获得数据库连接
             conn = JDBCUtils.getConnection();
            //获取传输
             st = conn.createStatement();
            //执行sql
            String sql="select * from account";
             rs = st.executeQuery(sql);
            //遍历结果集
            while(rs.next())
            {
                //获取id列的值
                String id=rs.getString("id");
                //获取username列的值
                String name=rs.getString("name");
                //获取money列的值
                String money=rs.getString("money");
                System.out.println(id+"\t"+name+"\t"+money);
            }
            //释放资源
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(rs, st, conn);
        }
    }

    //向user表里的所有数据
    @Test
    public void insertUser(){
        Connection conn=null;
        Statement st=null;
        try {
            //注册驱动 ,获得数据库连接
             conn = JDBCUtils.getConnection();
            //获取传输
             st = conn.createStatement();
            //执行sql
            String sql="insert into user values(null,'laowang','888')";
             int rows = st.executeUpdate(sql);
             System.out.println(rows+" rows affected");
            //释放资源
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(null, st, conn);
        }
    }
    
    //修改account表中id为2记录,money为900
    @Test
    public void updateAccount(){
        Connection conn=null;
        Statement st=null;
        try {
            conn=JDBCUtils.getConnection();
            st=conn.createStatement();
            String sql="update account set money=900 where id=2";
            int rows=st.executeUpdate(sql);
            System.out.println(rows+" rows affected");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(null, st, conn);
        }
    }
    //删除user表里id为8的记录
    @Test
    public void deleteUser(){
        Connection conn=null;
        Statement st=null;
        try {
            conn=JDBCUtils.getConnection();
            st=conn.createStatement();
            String sql="delete from user where id=8";
            int rows=st.executeUpdate(sql);
            System.out.println(rows+" rows affected");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(null, st, conn);
        }
    }

}

你可能感兴趣的:(JDBCUtils工具类——statement,非配置文件版实现CRUD)