有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用JDBC从mySQL获取特定列?

    PreparedStatement ps2;
    ResultSet rs2;

    String username = jTextField_username.getText();
    String userpassword = jTextField_userpassword.getText();

    String sql = "SELECT distinct kalanizin from users where username =?";
    String[] resultsetarray = null;

    try {

       ps2 = MyConnection.getConnection().prepareStatement(sql);
       ps2.setString(1, username);

       rs2 = ps2.executeQuery();
       String result = rs2.getString(0); // i want this String to hold the first result

大家好。我有一个问题一直在打我的头。正如标题中所说,使用JDBC时,我希望从数据库中获取一列。比如说

Select * from users where username = "blabla"

我希望Java执行这个查询并获得它找到的第一行。然后放入字符串或整数。正如你在上面看到的我糟糕的代码,它没有做到这一点。我试图通过使用语句来实现这一点,但仍然不起作用。有人能帮我吗?我们将不胜感激。 对不起,我的变量名太糟糕了,并且使用我的本地语言作为变量


共 (4) 个答案

  1. # 1 楼答案

    我的做法是:

    1)限制查询。您可以将限制作为1添加到查询中。我将鼓励您阅读,而不是提供样品

    2)例如,仅获取所需的列

    select u.age from users u where u.username=? 
    

    然后根据数据类型,您可以从结果集中获取它

  2. # 2 楼答案

    如果知道列名,可以使用^{}等方法代替getString(columnIndex)

    Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.

    columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column

  3. # 3 楼答案

    您缺少ResultSet#next调用

    根据示例代码,您可以执行以下操作:

    PreparedStatement ps2;
    ResultSet rs2;
    
    String username = jTextField_username.getText();
    String userpassword = jTextField_userpassword.getText();
    
    String sql = "SELECT distinct kalanizin from users where username =?";
    String[] resultsetarray = null;
    
    try {
       ps2 = MyConnection.getConnection().prepareStatement(sql);
       ps2.setString(1, username);
    
       rs2 = ps2.executeQuery();
       if(rs2.next()) { // moving to the first row
           String result = rs2.getString(1); // i want this String to hold the first result
       } else {
           // throw Exception ?
       }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    
  4. # 4 楼答案

    您请求的列以columnIndex=0开头,但列索引以1开头

    您可以使用我不久前使用的代码来查询整个表

    public List<Article> findAll() {
        Connection connection = jdbConnectionWrapper.getConnection();
        List<Article> articles = new ArrayList<>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM article");
            ResultSet resultSet = preparedStatement.executeQuery();
    
            while (resultSet.next()) {
                Article article = new Article();
    
                article.setId(resultSet.getLong(1));
                article.setName(resultSet.getString(2));
                article.setPrice(resultSet.getInt(3));
    
                articles.add(article);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return articles;
    }