jdbc

public class JdbcPractice {
    @Test
    public void testInsert() throws SQLException, ClassNotFoundException {
        // 1. 注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 2. 获取Connection对象
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/company_db",
                "root",
                "root");

        // 3. 获取Statement对象
        Statement stmt = connection.createStatement();

        // 4. 获取结果集
        String username = "zhangsan";
        String password = "345678";
        String balance = "1000";
        int i = stmt.executeUpdate("INSERT INTO tb_user(`username`, `password`, `balance`) " +
                                               "VALUES('" + username + "', '" + password + "', " + balance + ")");

        // 5. 处理结果集
        System.out.println(i);

        // 6. 释放资源
        stmt.close();
        connection.close();
    }
}
3.1.2 删除数据
public class JdbcPractice {
    @Test
    public void testDelete() throws SQLException, ClassNotFoundException {
        // 1. 注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 2. 获取Connection对象
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/company_db",
                "root",
                "root");

        // 3. 获取Statement对象
        Statement stmt = connection.createStatement();

        // 4. 获取结果集
        String id = "3";
        int i = stmt.executeUpdate("DELETE FROM tb_user WHERE id=" + id);

        // 5. 处理结果集
        System.out.println(i);

        // 6. 释放资源
        stmt.close();
        connection.close();
    }
}

posted on 2022-05-09 12:12  言语说  阅读(25)  评论(0编辑  收藏  举报

导航