連線資料庫實現查詢員工資訊
阿新 • • 發佈:2021-01-18
連線資料庫實現查詢員工資訊
按步驟操作實現查詢
package com.zheng.z; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC2 { private Connection conn = null; private Statement stmt = null; private ResultSet result = null; public void queryEMP() { try { // 1、載入驅動 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // 2、建立連線 String url = "jdbc:sqlserver://localhost:1433;databaseName=test"; String username = "zheng"; String pwd = "123"; conn = DriverManager.getConnection(url, username, pwd); // 3、建立sql語句 stmt = conn.createStatement(); String selectstr = "select * from info"; result = stmt.executeQuery(selectstr); // 4、處理結果集 System.out.println("員工編號:\t員工姓名:\t工作:"); while (result.next()) { System.out.println(result.getString("id") + "\t" + result.getString("name") + "\t" + "\t" + result.getString("job")); } } catch (Exception e) { e.getStackTrace(); } finally { // 5、關閉資源 try { if (result != null) { result.close(); result = null; } if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (Exception e) { e.getStackTrace(); } } } public static void main(String[] args) throws SQLException { // TODO 自動生成的方法存根 JDBC2 c = new JDBC2(); c.queryEMP(); } }
實現效果截圖