gpt4 book ai didi

java - java中参数化SELECT语句的问题

转载 作者:行者123 更新时间:2023-11-30 22:43:40 26 4
gpt4 key购买 nike

我遇到了参数化语句的问题,该语句返回错误“您的 SQL 语法中有错误靠近‘?’...我看不出问题出在哪里。任何帮助将是最受欢迎的。提前致谢。

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

}

最佳答案

替换

ResultSet rs = stmt.executeQuery(sql);

ResultSet rs = stmt.executeQuery();

第一个是继承的 Statement#executeQuery(String),它按原样执行查询,没有替换参数。

此外,只要您在 finally block 中关闭 JDBC 对象,就无需在 try block 中关闭它们。

关于java - java中参数化SELECT语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30278703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com