javaweb—JDBC資料庫增刪查改
一JDBC的增刪改
Ø Statement:用於執行靜態的sql語句
1.增加[insert]
2.更新[update]
3.刪除[delete]
增刪改都自需要用到executeUpdate()方法就可以了。
Ø PrepareStatement:用於執行預編譯sql語句
連線和關閉的程式碼:
package cn.proj_jdbc.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.Statement; public class JdbcUtil { /** * 連線資料庫資料 */ private static String url="jdbc:mysql://localhost:3306/schooldb"; private static String user="root"; private static String password="root"; /** * 單例模式 ,防止被建立 */ private JdbcUtil(){} /** * 註冊驅動程式 */ { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("驅動註冊程式出錯"); } } /** * 獲取連線物件 * @throws SQLException */ public static Connection getConnection() throws SQLException{ return DriverManager.getConnection(url,user,password); } /** * 關閉連線物件 * @throws SQLException */ public static void Close(Connection conn,Statement statement) throws SQLException{ if(statement!=null){ statement.close(); } if(statement!=null){ conn.close(); } } public static void Close(Connection conn,PreparedStatement statement,ResultSet resultSet) throws SQLException{ if(resultSet!=null){ resultSet.close(); } if(statement!=null){ statement.close(); } if(statement!=null){ conn.close(); } } } |
1.增加[insert]
2.更新[update]
3.刪除[delete]
4.查詢[select]
Mysql不支援sql緩衝區優化,所以statement和preparestatement執行效率是一樣的,但是sqlserver和oracle支援。但是還是推薦用preparestatement。
Ø CallableStatement:執行儲存過程
1.帶有輸出引數的儲存過程
2.帶有輸出引數的儲存過程
事務的使用