JDBC_11_PreparedStatement(增删改操作)

PreparedStatement(增删改操作)

* 代码:

    ```
        import javax.swing.plaf.nimbus.State;
        import java.sql.*;

        public class JDBCTest08 {
            public static void main(String[] args) {

                //创建数据库连接对象
                Connection connection=null;
                PreparedStatement preparedstatement=null;
                int count=0;

                try {
                    //注册驱动
                    Class.forName("com.mysql.cj.jdbc.Driver");

                    //获取连接
                    connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employ?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai",
                            "root","123456");

                    //获取预编译数据库对象,并编译SQL语句
                    //  String sql="insert into dept (deptno,dname,loc)values(?,?,?)";  插入

                    //  String sql="DELETE FROM dept WHERE deptno = ?";                 删除

                        String sql="UPDATE DEPT SET dname = ? ,loc=? WHERE deptno = ?";  更新

                    preparedstatement=connection.prepareStatement(sql);

                    //给占位符传值
                    preparedstatement.setString(1,"研发部");
                    preparedstatement.setString(2,"北京");
                    preparedstatement.setInt(3,90);

                    //执行SQL语句
                    count=preparedstatement.executeUpdate();

                    //输出
                    System.out.println(count==1?"插入成功":"插入失败");

                } catch (ClassNotFoundException | SQLException e) {
                    e.printStackTrace();
                }finally {

                   // 增删改
                    if(preparedstatement!=null){
                        try {
                            preparedstatement.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }

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

                }

            }
        }

JDBC_11_PreparedStatement(增删改操作)

上一篇:数据库基础一


下一篇:adb常用命令(一)