我遇到了一个参数化语句的问题,该语句返回错误'你的SQL语法错误附近' ... ...我无法看到问题出在哪里。任何帮助都是最受欢迎的。 Thx提前。
import java.sql.*;
import java.util.LinkedList;
import java.util.ListIterator;
public class ReadDb {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/HarmonicEngine";
static final String USER = "*********";
static final String PASS = "*******";
private static LinkedList<PitchStats> chord = new LinkedList<PitchStats>();
private static int chnum;
ReadDb(int chordnum) {
chnum = chordnum;
}
public static void main(String[] args) {
// *TEST*
chnum = 1;
LinkedList<PitchStats> trial = ReadExecute();
ListIterator<PitchStats> listIterator = trial.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
public static LinkedList<PitchStats> ReadExecute() {
Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Creating statement....");
String sql = "SELECT pitch_name, pitch_reg, move_num, block_num, prog_num, "
+ "sustain FROM sample1 WHERE chord_num = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, chnum);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String pitchname = rs.getString("pitch_name");
int pitchreg = rs.getInt("pitch_reg");
int movenum = rs.getInt("move_num");
int blocknum = rs.getInt("block_num");
int prognum = rs.getInt("prog_num");
boolean sustained = rs.getBoolean("sustain");
PitchStats thisPitch = new PitchStats(pitchname, pitchreg,
movenum, blocknum, prognum, chnum, sustained);
chord.add(thisPitch);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
System.out.println("Goodbye!");
}
return chord;
}
}
答案 0 :(得分:0)
替换
ResultSet rs = stmt.executeQuery(sql);
与
ResultSet rs = stmt.executeQuery();
第一个是继承的Statement#executeQuery(String)
,它按原样执行查询,没有替换参数。
只要您在try
块中关闭它们,就无需关闭finally
块中的JDBC对象。