連接資料庫所需要的程式Class及編碼UTF-8
@page import = "java.sql.*"
@page contentType="text/html" pageEncoding="UTF-8"
try{
//載入資料庫驅動程式
Class.forName("com.mysql.jdbc.Driver");
try {
//建立連線
String url="jdbc:mysql://localhost/";
Connection con=DriverManager.getConnection(url,"root","1234");
if(con.isClosed())
out.println("連線建立失敗");
else{
//選擇資料庫
con.createStatement().execute("use adress_id");
在頭尾中間擺放SQL的程式部分 (需要資料庫操作的部分)
//關閉連線
con.close();
}
}
catch (SQLException sExec) {
out.println("SQL錯誤"+sExec.toString());
}
}
catch (ClassNotFoundException err) {
out.println("class錯誤"+err.toString());
}
String sql = "INSERT `表格名稱`(`欄位1`,`欄位2`,`欄位3`,`欄位4`,`欄位5`) VALUES ('欄位1的數值','欄位2的數值','欄位3的數值','欄位4的數值','欄位5的數值')";
//SQL語法,這裡需要用單引號, 59有無單引號都可
boolean no= con.createStatement().execute(sql); //執行成功傳回false
//int no=con.createStatement().executeUpdate(sql); //可回傳異動數
if (!no)
//顯示結果
out.println("新增成功");
else
out.println("新增失敗");
SQL語法拆解
INSERT `表格名稱`(`欄位1`,`欄位2`,`欄位3`,`欄位4`,`欄位5`)
//記得要包含所有欄位 除了 AI Key
VALUES ('欄位1的數值','欄位2的數值','欄位3的數值','欄位4的數值','欄位5的數值')