JDBC 选择记录
2018-03-21 14:12 更新
JDBC教程 - JDBC选择记录
以下代码显示如何从数据库表中检索数据。
它发出一个select命令,并通过读取 ResultSet
获取结果接口。
例子
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Main { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) throws Exception { Connection conn = null; Statement stmt = null; Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Deleting database..."); stmt = conn.createStatement(); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); String sql = "SELECT id, first, last, age FROM Person"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("firstName"); String last = rs.getString("lastName"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); stmt.close(); conn.close(); } }
示例PreparedStatement
以下代码显示了如何使用Oracle JDBC驱动程序通过PreparedStatement执行select语句。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Main { private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase"; private static final String DB_USER = "user"; private static final String DB_PASSWORD = "password"; public static void main(String[] argv) throws Exception { Connection dbConnection = null; PreparedStatement preparedStatement = null; Class.forName(DB_DRIVER); dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); String selectSQL = "SELECT USER_ID, USERNAME FROM Person WHERE USER_ID = ?"; preparedStatement = dbConnection.prepareStatement(selectSQL); preparedStatement.setInt(1, 1001); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String userid = rs.getString("USER_ID"); String username = rs.getString("USERNAME"); System.out.println("userid : " + userid); System.out.println("username : " + username); } preparedStatement.close(); dbConnection.close(); } }
以上内容是否对您有帮助:
更多建议: