標籤:
1 package qddx.JDBC; 2 import java.sql.*; 3 4 public class JDBC_Connection { 5 static String driverName = "com.mysql.jdbc.Driver";//驅動名 6 static String url="jdbc:mysql://localhost/bbs";//地址 7 static String userName="root";//帳號 8 static String passWord = "674768166ws";//密碼 9 static {10 try{//串連驅動11 Class.forName(driverName);12 }catch(ClassNotFoundException e){13 e.printStackTrace();14 }15 }16 //串連資料庫17 public static Connection getConnection(){18 Connection conn = null;19 try{20 conn = (Connection)DriverManager.getConnection(url,userName,passWord);21 System.out.println("資料庫連接成功");22 conn.setAutoCommit(false);// 設定事務不自動認可23 }catch(SQLException e){24 e.printStackTrace();25 }26 System.out.println("已經串連");27 return conn;28 }29 //關閉資料庫30 public static void free(ResultSet rs,Connection conn,Statement stmt){31 try{32 if(rs!=null){33 rs.close();34 rs=null;35 }36 }catch(SQLException e){37 e.printStackTrace();38 }finally{39 try{40 if(conn!=null){41 conn.close();42 conn = null;43 }44 if(stmt !=null){45 stmt.close();46 stmt=null;47 }48 }catch(SQLException e){49 e.printStackTrace();50 }51 }52 }53 public static void main(String[] args) {54 JDBC_Connection.getConnection();//啟動55 }56 57 }
JDBC中串連MySQL資料庫