如何从 DB2 数据库获取值并将其分配给字符串值?

Mal*_*oth -1 java database string db2 methods

我正在使用连接到 DB2 数据库的 java 应用程序。我想要做的是从我查询的 DB2 表中获取一个值并将其分配给 java 中的字符串值,你能教我怎么做吗?我自己尝试过,我会向您展示我的代码,但我认为并知道这是错误的,请帮助...

public class GetValueFromDB2 implements ActionListener{
    static String value;

    public void actionPerformed(ActionEvent e){
      Object source = e.getSource();
      if(source==testValue){ //testValue = a button to test my results
        setValue(getValue());
        JOptionPane.showMessageDialog(null, value);
      }
    }

    public static void main(String[] args){
      //GUI Implementations here...
    }

    public static void setValue(String val){
    try{
      Connection con = DriverManager.getConnection("jdbc:db2://localhost:50000/db","username","password");          
      String sql = "select column1 from \"user\".\"mytable\" where column2='abc'";
      Statement st = con.createStatement();
      ResultSet rs = st.executeQuery(sql);
      val = rs.getString(1); //I think this is the part I'm mistaken
      value = val;
    }catch(SQLException e){
      JOptionPane.showMessageDialog(null, e);
    }
    }

    public static String getValue(){
      return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的数据库中的表是这样的:

"table: mytable, schema: user"
column1            column2
--------           --------
john               abc
jeff               xyz
ian                123
Run Code Online (Sandbox Code Playgroud)

所以基本上, JOptionPane 应该将“john”显示为字符串输出,这就是我想要做的,请帮助我,我真的非常需要这个。

  • 我 100% 确定我的数据库已连接,只是我无法获得我想要的值,因为在某种程度上我正在执行错误的方法。

JB *_*zet 5

rs.next()您在获取值之前忘记调用:

if (rs.next()) {
    val = rs.getString(1);
}
Run Code Online (Sandbox Code Playgroud)

如果不调用rs.next(),光标不会指向任何行。