我已经连接到一个 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.getInt
或 rs.getString
中,您可以从 1
开始传递 column_id
,但我更喜欢传递 column_name
因为它的信息量更大,因为您不必查看数据库 table
index
是 column
.
更新: 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
关于Java - 从 MySQL 数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12041354/