---
title: "java.sql.SQLException: '@P0' 附近有语法错误"
author: "bolan392"
date: "2010-09-07T14:11:21Z"
tags: []
categories: ["企业架构"]
slug: "java-sql-sqlexception-p0"
draft: false
lastmod: "2010-09-07T14:11:21Z"
id: 757471
url: "https://bolan392.iteye.com/blog/757471"
---

执行的代码如下：

 

```
        String sql = ”select top ? * from bbs_posts where p_fid=? order by p_addtime desc”;
        prepStmt = conn.prepareStatement(sql);
        prepStmt.setInt(1, xxx);
        prepStmt.setInt(2, xx);
        prepStmt.executeQuery()
```

 

控制台报错:java.sql.SQLException: ['@P0'](mailto:'@P0') 附近有语法错误

查了一下原因：sql不支持为select top ? 预编译

使用字符串的动态拼接解决:

 

```
        String sql = ”select top %s * from bbs_posts where p_fid=? order by p_addtime desc”;
        sql = String.format(sql, num);
```

其中，参数num为将要拼接到SQL语句中的参数。