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

标签 java mysql database jdbc

    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 执行此查询并获取它找到的第一行。然后放入字符串或整数。正如您在顶部看到我糟糕的代码一样,它无法做到这一点。我试图通过使用语句来完成此操作,但它仍然不起作用。谁能帮我?那将不胜感激。 附言。抱歉我糟糕的变量名和使用我的本地语言作为变量

最佳答案

如果你知道列名你可以使用像getString(columnLabel)这样的方法而不是 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

关于java - 如何使用 JDBC 从 mySQL 获取特定列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50606143/

相关文章:

java - 无法将数据发送到另一个方法

MySQL 从表 1 中选择一个 SUM,并在表 2 中加入 SUM

php - 有什么是 PHP with CodeIgniter 可以做而 Ruby on Rails 3 不能做的吗?

java - 在linux中启动一个类似服务的jar文件

mysql - 获取表中每个条目组合的公共(public)联接

html - php从mysql中获取多行

mysql - 什么是索引?

java - XPath 如何从 html 文档中检索表格单元格的值

java - 相同的字母给出不同的 ASCII 码

java - 为什么 for-each 循环适用于数组? ( java )