この問題で先に進めなくなってから2日が経ちました。私はこれが非常に簡単であることを他の人に知っています。JDBC を 3 か月間学習し始めたばかりです。
問題
- 結果セットから値を取得できません。
- それは私にヌル値を与えています。
私のコードについて読んでコメントしたところによると、ストアドプロシージャは結果セットを返すことができますが、私の場合はそうではありません。結果セットをループするべきではありません。したがって、値を取得したい場合は、結果セットではなく Callable ステートメント自体で適切な getXXX() メソッドを呼び出す必要があります。したがって、コードを Result Set ブロックから削除し、それを Callable Statement ブロックに配置すると、null 値が返されます。値を正しく取得できません。
CREATE TABLE allsections_list
(
SECTION_ID INT PRIMARY KEY,
SECTION_NAME VARCHAR(50) NULL
)
DELIMITER @@
DROP PROCEDURE getSECTION_NAME @@
CREATE PROCEDURE enrollmentdb.getSECTION_NAME
(IN myID INT, OUT myName VARCHAR(50))
BEGIN
SELECT SECTION_NAME INTO myName FROM allsections_list WHERE SECTION_ID = myID;
END @@
DELIMITER ;
Call 構文を使用してストアド プロシージャを取得しようとすると。正常に既存のレコードを取得しています。
SET @myID = 9;
CALL getSECTION_NAME(@myID, @myName);
SELECT @myName;
ここでわかるように、正しい値を取得しています。しかし、結果セットを使用して取得すると、null 値が返されます。
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String searchSection = Section_SearchSection_Textfield.getText();
String searchSection_Name = Section_SectionName_TextField.getText();
int sectionID = 0;
if (searchSection.isEmpty())
{
JOptionPane.showMessageDialog(null, "Please fill up this fields");
}
else
try (Connection myConn = DBUtil.connect();
CallableStatement myFirstCs = myConn.prepareCall("{call getSECTION_NAME(?,?)}"))
{
myFirstCs.setInt(1, sectionID);// I set the ID for Primary Key
myFirstCs.registerOutParameter(2, Types.VARCHAR);
boolean hasresults = myFirstCs.execute();
if (hasresults)
{
try (ResultSet myRs = myFirstCs.getResultSet())
{
int counter = 0;
while (myRs.next())
{
sectionID = myRs.getInt("SECTION_ID");
System.out.print(sectionID);
counter++;
}//end of while
}//end of resultset
}//end of if
String sectionName = myFirstCs.getString(2);
Section_SectionName_TextField.setText(sectionName);//Set the value of text
Section_SectionName_TextField.setEnabled(true);//Set to enable
System.out.print(sectionName);
}//end of connection
catch (SQLException e)
{
DBUtil.processException(e);
}
}
既存のレコードを検索する場合にやりたいことは、次のようになります。
私の投稿を読んでくれてありがとう。どんな助けでも感謝します。ありがとう!:)