每次在面試時被問到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();
}
} |