在Java中向MySQL添加数据,statement

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class QueryDemo {
    public static void main(String[] args) throws Exception {
        QueryDemo demo = new QueryDemo();
        /*
        List<Dept> list = demo.findAllDept();
        for (Dept dept : list) {
            System.out.println(dept);
        }
        */
        Dept dept = new Dept(0, "test", 1);
        System.out.println(demo.saveDept(dept));
    }

    // 查找所有的部门
    public List<Dept> findAllDept() throws ClassNotFoundException, SQLException {
        // 1.注册数据库驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 2.与数据库建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://@localhost:3306/oaec", "root", "root");
        // 3.创建用来执行SQL语句的Statement对象
        Statement stmt = conn.createStatement();
        // 4.执行SQL语句
        String sql = "select id,name,region_id from s_dept";
        // 执行查询:executeQuery(String sql)==>ResultSet,结果集
        // 增删改:executeUpdate(String sql)==>int,影响的行数
        ResultSet rs = stmt.executeQuery(sql);
        List<Dept> list = new ArrayList<Dept>();
        // 5.处理结果集(针对查询)
        while (rs.next()) {
            // 一次循环处理一行,一行转换成一个对象
            Dept dept = new Dept(rs.getInt(1), rs.getString(2), rs.getInt(3));
            list.add(dept);// 添加到集合
        }
        // 6.释放资源
        // ResultSet-->Statement-->Connection
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
        return list;
    }

    // 添加一个部门
    public int saveDept(Dept dept) throws ClassNotFoundException, SQLException {
        // 1.注册数据库驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 2.与数据库建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://@localhost:3306/oaec", "root", "root");
        // 3.创建用来执行SQL语句的Statement对象
        Statement stmt = conn.createStatement();
        // 4.执行SQL语句
        String sql = "insert into s_dept (name,region_id) "
                + "values ('"+dept.getName()+"',"+dept.getRegionId()+")";
        //增删改:executeUpdate(String sql)==>int,影响的行数
        int rows = stmt.executeUpdate(sql);
        // 6.释放资源
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
        return rows;
    }
}

猜你喜欢

转载自www.cnblogs.com/alpha-cat/p/11393486.html