即先定义占位符,后再用 setString(下标从1开始,对象参数) 方法填充占位
小编举个栗子
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.sql.*;
public class FindGradeUsingPreparedStatement extends Application {
private PreparedStatement preparedStatement;
private TextField sno = new TextField(); //学号文本域
private TextField cname = new TextField(); //课程名称文本域
private Label lblStatus = new Label(); //显示的成绩
@Override
public void start(Stage primaryStage) {
initializeDB();
Button btShowGrade = new Button("点击查询");
HBox hBox = new HBox(5); //水平面板
hBox.getChildren().addAll(new Label("学号:"), sno, new Label("课程名:"), cname, (btShowGrade));
VBox vBox = new VBox(20); //垂直面板
vBox.setPadding(new Insets(20));
vBox.getChildren().addAll(hBox, lblStatus);
sno.setPrefColumnCount(12);
cname.setPrefColumnCount(12);
btShowGrade.setOnAction(e -> showGrade()); //注册处理事件
Scene scene = new Scene(vBox, 540, 100);
primaryStage.setTitle("成绩查询系统");
primaryStage.setScene(scene);
primaryStage.show();
}
private void initializeDB() { //连接
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("加载Driver类成功。");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabook?useSSL=false&useUnicode=true&characterEncoding=utf8", "root","123456");
System.out.println("连接MySQL的root账户成功。");
String queryString = "select A.degree from sc A,course B where sno=? and cname=? and A.cno=B.cno;"; //以?做占位符MySQL语句
preparedStatement = connection.prepareStatement(queryString); //构建对象
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private void showGrade() {
String ssn = sno.getText(); //输入的学号文本
String courseId = cname.getText(); //输入的课程名称
try {
preparedStatement.setString(1, ssn); //填充第一个占位符?为ssn
preparedStatement.setString(2, courseId);//填充第二个占位符?为courseId
ResultSet rset = preparedStatement.executeQuery(); //执行查询语句
if (rset.next()) {
String degree = rset.getString(1); //读取一列
lblStatus.setText("你的成绩是:" + degree + " 分");
} else {
lblStatus.setText("对不起,未找到。");
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}