Java - 从 MySQL 数据库中获取数据

标签 java mysql sql database jsp

我已经连接到一个 MySQL 数据库,它包含四个字段(第一个是 ID,后面的每个都包含 varchar 字符串)。

我正在尝试获取数据库的最后一行并检索字段的内容,以便我可以将它们设置为变量(一个 int 和三个字符串)并在以后使用它们。

到目前为止,我已经有了最低限度的连接,我该从哪里开始?如您所见,我曾尝试编写一个 SQL 语句来获取最后一行,但从那里开始一切都出错了,我不知道如何将其拆分为单独的字段。

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");

Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();

最佳答案

给你:

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");

Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) { 
 int id = rs.getInt("first_column_name"); 
 String str1 = rs.getString("second_column_name");
}

con.close();

rs.getIntrs.getString 中,您可以从 1 开始传递 column_id,但我更喜欢传递 column_name 因为它的信息量更大,因为您不必查看数据库 table indexcolumn.

更新: rs.next

boolean next() throws SQLException

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set

reference

关于Java - 从 MySQL 数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12041354/

相关文章:

java - 如何为 BinaryTree<T> 类编写 left() 和 right() 方法

java - 如何使 oshi.hardware.Sensors 信息可供获取。能做到吗?

sql - 是否允许在 have 子句中使用 over()?

php - 存储时间 - 使用 Time 或 Int 字段? (PHP 和 MySQL 数据库)

php - 表和连接的 SQL 语法有误

arm - 如何解决错误 "Exception in thread "AWT-EventQueue- 0"java.lang.NullPointerException:"?

java - 使用 Repast Simphony 2.0 Eclipse 在关闭透视图和关闭应用程序后不再打开

java - 如何解决第 1 行第 "Incorrect integer value: ' 列的错误 'type_id' null'?

mysql - 当查询结果返回不匹配时需要显示替代文本

php - 如何以 ='background-image' 标签风格对来自 mysql 的图像进行编码