其他分享
首页 > 其他分享> > jdbc

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();
    }
}

标签:jdbc,stmt,connection,Statement,mysql,close
来源: https://www.cnblogs.com/speak-please/p/16248728.html