Java連線MySQL實現增刪改查
現在許多框架都對資料庫進行了封裝,但是我們剛開始學習時,更好的還是使用Java手寫sql語句,進行相關操作,以便於我們瞭解Mysql呼叫機制。
本文中我們實現使用者註冊的基礎操作:從jsp得到使用者名稱密碼->驗證使用者是否存在->如果使用者不存在則插入資料
Java程式碼如下:
最開始學習的情況下,我們的jsp應該呼叫的是一個servlet,將下文doSignIn方法中的內容放在你的doGet內,不要完全參考我的。
SQL語句部分,示例只是最基礎的username和password欄位 還有一個未顯示的自增主鍵id欄位,按需修改。
我的Jsp頁面傳過來的欄位是email和password1,是延續上文連結中的Form,這些比較基礎就不多說了。
public String doSignIn(HttpServletRequest request){ //這一行不用參考,下文中的程式碼放在Servlet中即可,return返回值也根據你的需要進行修改
String username = request.getParameter("email");
String password = request.getParameter("password1");
//宣告Connection物件
Connection con;
//驅動程式名
String driver = "com.mysql.jdbc.Driver";
//URL指向要訪問的資料庫名mydata
String url = "jdbc:mysql://localhost:3306/test";
//MySQL配置時的使用者名稱
String user = "root";
//MySQL配置時的密碼
String pwd = "123456";
//遍歷查詢結果集
try {
//載入驅動程式
Class.forName(driver);
//1.getConnection()方法,連線MySQL資料庫!!
con = DriverManager.getConnection(url
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.建立statement類物件,用來執行SQL語句!!
Statement statement = con.createStatement();
//要執行的SQL語句
String sql = "select * from user where username = '"+username+"'";
//3.ResultSet類,用來存放獲取的結果集!!
System.out.println(sql);
ResultSet rs = statement.executeQuery(sql);
if(!rs.next()){
sql="insert into user (username,password) values ('"+username+"','"+password+"')";
System.out.println(sql);
try {
statement.execute(sql);
return "success";
} catch (Exception e) {
e.printStackTrace();
System.out.println("資料插入失敗!");
}
}else{
System.out.println("使用者已經存在!");
}
System.out.println(rs);
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//資料庫驅動類異常處理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
// 資料庫連線失敗異常處理
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("資料庫資料成功獲取!!");
}
return"signin";
}