每次在面試時被問到jdbc的數據路鏈接過程都卡著,這次不怕了,背會了。。。
第一個 ,比較粗糙的 try{ ? Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException e) {} //定義所要用到的三個數據庫應用對象 Connection con=null; //連接對象 Statement sql=null; //Statement對象(SQL語句) ResultSet rs=null; //結果集對象 //進行數據源的連接 try{ ? con=DriverManager.getConnection ("jdbc:mysql://localhost/scutcs","","");//連接數據庫的url 用戶名和密碼 sql=con.createStatement(); String to="Select * From user1 Where username='"+username+"'"; rs=sql.executeQuery(to); //根據所定義的Statement執行生成相應的結果集并存在RS中 if(rs.next()) //判斷結果集是否為空,如果不為空則表示有記錄 { out.print("<script>alert('用戶名 "+xm+"已存在,請另選一個!');history.back();</script>");//如果存在返回注冊頁面 } else {如果不存在就向數據庫添加一條記錄} } catch (SQLException e) ? { out.print(e); ? } 第二個 ,作為公共類比較完整些的? 把部分的定義為單個函數方便調用 import java.sql.*; public class DB { public static Connection getConn() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/shopping?user=root&password=123456"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static PreparedStatement prepare(Connection conn, String sql) { PreparedStatement pstmt = null; ? try { if(conn != null) { pstmt = conn.prepareStatement(sql); } } catch (SQLException e) { e.printStackTrace(); } return pstmt; } public static PreparedStatement prepare(Connection conn, String sql, int autoGenereatedKeys) { PreparedStatement pstmt = null; ? try { if(conn != null) { pstmt = conn.prepareStatement(sql, autoGenereatedKeys); } } catch (SQLException e) { e.printStackTrace(); } return pstmt; } public static Statement getStatement(Connection conn) { Statement stmt = null; ? try { if(conn != null) { stmt = conn.createStatement(); } } catch (SQLException e) { e.printStackTrace(); } return stmt; } /* public static ResultSet getResultSet(Connection conn, String sql) { Statement stmt = getStatement(conn); ResultSet rs = getResultSet(stmt, sql); close(stmt); return rs; } */ public static ResultSet getResultSet(Statement stmt, String sql) { ResultSet rs = null; try { if(stmt != null) { rs = stmt.executeQuery(sql); } } catch (SQLException e) { e.printStackTrace(); } return rs; } public static void executeUpdate(Statement stmt, String sql) { try { if(stmt != null) { stmt.executeUpdate(sql); } } catch (SQLException e) { e.printStackTrace(); } } public static void close(Connection conn) { try { if(conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } public static void close(Statement stmt) { try { if(stmt != null) { stmt.close(); stmt = null; } } catch (SQLException e) { e.printStackTrace(); } } ? |
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
