Java如何从表中查询记录?
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JdbcQueryExample { //数据库连接信息 private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) throws Exception { //获取与数据库的连接。 try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { //创建一个语句对象。 Statement statement = connection.createStatement(); //执行查询命令以选择isbn和书名 //books表。执行查询返回一个ResultSet //对象,这是我们执行查询的结果。 String query = "SELECT isbn, title, published_year FROM books"; ResultSet books = statement.executeQuery(query); //为了获得statement.executeQuery返回的值,我们 //需要迭代books对象直到最后一项。 while (books.next()) { //要从ResultSet对象获取值,我们可以调用 //与列的数据类型相对应的方法 //在数据库表中。在下面的示例中,我们调用 //books.getString(“isbn”)获取该书的ISBN"isbn") to get the book's ISBN //信息。 System.out.println(books.getString("isbn") + ", " + books.getString("title") + ", " + books.getInt("published_year")); } } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>