讀取連線資料庫資訊
阿新 • • 發佈:2021-10-25
/* 從屬性資原始檔中讀取連線資料庫資訊 實際開發中不建議把連線資料庫的資訊寫死到java程式中 配置檔案jdbc.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/bjpowernode user=root password=123456 */ import java.sql.*; import java.url.*; public class JDBCTest04{ public static void main(String [] args){ //使用資源繫結器繫結屬性配置檔案 ResourceBundle bundle=ResourceBundle.getBundle("jdbc"); String driver=bundle.getString("driver"); String url=bundle.getString("url"); String user=bundle.getString("user"); String password=bundle.getString("password"); Connection conn=null; Statement stmt=null; try{ //1.註冊驅動 Class.forName(driver); //2.獲取連結 conn=DriverManager.getConnection(url,user,password); //3.獲取資料庫操作物件 stmt=conn.createStatement(); //4.執行sql語句 String sql="update dept set dname='銷售部',loc='天津' where deptno=20"; int count=stmt.executeUpdate(sql); System.out.println(count==1?"更新成功":"更新失敗"); }catch(Exception e){ e.printStackTrace(); }finally{ //6.釋放資源 if(smt!=null){ try{ smt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn!=null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }