JDBC连接示例

2、首先获取Connection

获取连接代码

    private static Connection getConn() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://ip:端口/数据库名?连接参数";
        String username = "用户名";
        String password = "密码";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

2、使用连接进行增删

2.1 insert示例

        private static void insert() throws SQLException {
        //1.获取连接
        Connection conn = getConn();
        try {
            conn.setAutoCommit(false);
            //2.获得预处理对象
            String sql = "insert into table_user (id,name) values (?,?)";
            PreparedStatement pstmt;
            pstmt = (PreparedStatement) conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
            //3.SQL语句占位符设置实际参数
            pstmt.setLong(1, 1L);
            pstmt.setString(2, "Tony Stark");
            //4.执行SQL语句
            int line = pstmt.executeUpdate();
            conn.commit();
            System.out.println("更新记录数"+ line);

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //5.关闭资源
            conn.close();
        }
    }

delete示例

 private static void delete() {
        //1.获取连接
        Connection conn = getConn();
        try {
        	//2.获得预处理对象
            String sql = "delete from table_user where id = 1";
            Statement statement = connection.createStatement();
            //4.执行SQL语句
            int result = statement.executeUpdate(sql);
            if (result != 0) {
                System.out.println("操作成功,受影响" + result + "行");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            conn.close();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值