日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

【JavaWeb】JDBC的基本操作和事务控制+登录和转账案例

發布時間:2024/7/5 java 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【JavaWeb】JDBC的基本操作和事务控制+登录和转账案例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 JDBC操作數據庫

1.1 連接數據庫

首先導入jar包到lib

public class JdbcDemo1 {public static void main(String[] args) throws ClassNotFoundException, SQLException {//1.注冊驅動Class.forName("com.mysql.jdbc.Driver");//2.獲取數據庫連接對象Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "123456");//3.定義sql語句String sql = "update account set balance = 500 where id = 1";//4.獲取執行sql的對象 statementStatement statement = conn.createStatement();//5.執行sqlint count = statement.executeUpdate(sql);//6.處理結果System.out.println(count);//7.釋放資源statement.close();conn.close();} }

1.2 數據庫相關對象詳解

1.2.1DriverManager:驅動管理對象

  • 注冊驅動
    -Class.forName("com.mysql.jdbc.Driver");
    com.mysql.jdbc.Driver類中存在靜態代碼塊
    MySQL 5 之后的驅動jar包可以省略注冊驅動的步驟

  • 獲取數據庫連接
    -DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "password");
    url語法:jdbc:mysql:// [ip地址] : [端口號] / [數據庫名稱]
    如果連接的是本機的mysql 默認是3306 url可以簡寫為"jdbc:mysql:///db2"

  • 1.2.2 Connection:數據庫連接對象

  • 獲取用于執行sql的對象
    • Statement createStatement();
    • PreparedStatement preparedStatement(String sql);
  • 管理事務
    • 開啟事務:void setAutoCommit(boolean autoCommit) 設置參數為false即開啟事務
    • 提交事務:void commit()
    • 回滾事務:void rollback()

    1.2.3 Statement:執行sql的對象

  • 執行sql
    • boolean execute(String sql):可以執行任意sql
    • int executeUpdate(String sql):執行DML(C、U、D)語句、DDL(表、庫)語句,返回值是受影響的行數。判斷DML是否執行成功,返回值>0則成功。
    • ResultSet executeQurey(String sql):執行DQL(R)語句

    1.2.4 ResultSet:結果集對象

  • 獲取封裝好的查詢結果
    -next():游標向前移動一行
    -getXxx(int column):獲取第column列的Xxx類型的數據 索引從1開始
    -getXxx(String name):獲取命名為name字段的Xxx類型的數據
  • 1.2.5 PreparedStatement:

  • sql注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接,會造成安全問題。
    sql:-select * from user where username = 'xxxx' and password = 'a' or 'a' = 'a'
  • 使用PreparedStatement可以解決sql注入問題
  • 預編譯的sql:參數使用?作為占位符
  • sql的參數使用?作為占位符。
  • 獲取執行sql對象使用preparedStatement
  • 給占位符賦值setXxxxx(位置編號,值),注意編號從1開始。
  • 效率高,且防止sql注入,后期都用這個,不再使用Statement對象
  • 1.3 基本操作練習

    增刪改

    public static void main(String[] args){Connection conn = null;Statement statement = null;try{Class.forName("com.mysql.jdbc.Driver");String sql = "insert into account values(null,'王五',3000)";conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "password");statement = conn.createStatement();int count = statement.executeUpdate(sql);if(count > 0){System.out.println("添加成功");}else {System.out.println("添加失敗");}}catch (ClassNotFoundException | SQLException e){e.printStackTrace();}finally {//避免空指針異常if(statement!=null){try {statement.close();}catch (SQLException e){e.printStackTrace();}}if(conn!=null){try {conn.close();}catch (SQLException e){e.printStackTrace();}}}}

    查詢

    public static void main(String[] args){Connection conn = null;Statement statement = null;ResultSet resultSet = null;try{Class.forName("com.mysql.jdbc.Driver");String sql = "select * from account";conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "password");statement = conn.createStatement();resultSet = statement.executeQuery(sql);while(resultSet.next()){int id = resultSet.getInt(1);String name = resultSet.getString("name");double balance = resultSet.getDouble(3);System.out.println(id+ " "+ name+" "+balance);}}catch (ClassNotFoundException | SQLException e){e.printStackTrace();}finally {//避免空指針異常if(resultSet!=null){try {resultSet.close();}catch (SQLException e){e.printStackTrace();}}if(statement!=null){try {statement.close();}catch (SQLException e){e.printStackTrace();}}if(conn!=null){try {conn.close();}catch (SQLException e){e.printStackTrace();}}}}

    新建一個Account類型的JavaBean
    讀取表到Account類型的列表中

    package jdbc;import domain.Account;import java.sql.*; import java.util.ArrayList; import java.util.List;public class JdbcDemo2 {public List<Account> findAll(){Connection conn = null;Statement stmt = null;ResultSet rs = null;List<Account> accounts = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "123456");String sql = "select * from account";stmt = conn.createStatement();rs = stmt.executeQuery(sql);accounts = new ArrayList<>();Account account = null;while(rs.next()){account = new Account();int id = rs.getInt("id");String name = rs.getString("name");double balance = rs.getDouble("balance");account.setBalance(balance);account.setId(id);account.setName(name);accounts.add(account);}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally {if(rs != null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if(stmt != null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if(conn != null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}return accounts;}public static void main(String[] args) {List<Account> all = new JdbcDemo2().findAll();for(Account a : all){System.out.println(a);}} }

    1.4 抽取JDBC的工具類

    簡化代碼的書寫
    編寫jdbc配置文件,設置url、user、password、driver
    jdbc.properties

    url=jdbc:mysql:///db2 user=root password=password driver=com.mysql.jdbc.Driver package jdbc;import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties;public class JdbcUtil {private static String url;private static String user;private static String password;private static String driver;//讀取配置文件 用靜態代碼塊 只需要讀取一次static {try{Properties pro = new Properties();//獲取src路徑下的文件的方式ClassLoader加載器ClassLoader classLoader = JdbcUtil.class.getClassLoader();URL res = classLoader.getResource("jdbc.properties");String path = res.getPath();pro.load(new FileReader(path));url = pro.getProperty("url");user = pro.getProperty("user");password = pro.getProperty("password");driver = pro.getProperty("driver");Class.forName(driver);}catch (IOException e){e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}public static Connection getConnection() throws SQLException {return DriverManager.getConnection(url,user,password);}public static void close(Statement stmt, Connection conn){if(stmt!=null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if(conn!=null){try {conn.close();}catch (SQLException e){e.printStackTrace();}}}public static void close(Statement stmt, Connection conn, ResultSet rs){if(rs!=null){try{stmt.close();}catch (SQLException e){e.printStackTrace();}}if(stmt!=null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if(conn!=null){try {conn.close();}catch (SQLException e){e.printStackTrace();}}} }

    使用工具類

    package jdbc;import domain.Account;import java.sql.*; import java.util.ArrayList; import java.util.List;public class JdbcDemo2 {public List<Account> findAll(){Connection conn = null;Statement stmt = null;ResultSet rs = null;List<Account> accounts = null;try {conn = JdbcUtil.getConnection();String sql = "select * from account";stmt = conn.createStatement();rs = stmt.executeQuery(sql);accounts = new ArrayList<>();Account account = null;while(rs.next()){account = new Account();int id = rs.getInt("id");String name = rs.getString("name");double balance = rs.getDouble("balance");account.setBalance(balance);account.setId(id);account.setName(name);accounts.add(account);}} catch (SQLException e) {e.printStackTrace();}finally {JdbcUtil.close(stmt,conn,rs);}return accounts;}public static void main(String[] args) {List<Account> all = new JdbcDemo2().findAll();for(Account a : all){System.out.println(a);}} }

    2 登錄案例

    public class JdbcDemo3 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入用戶名:");String username = sc.nextLine();System.out.println("請輸入密碼:");String password = sc.nextLine();boolean check = login(username, password);if(check){System.out.println("登錄成功");}else{System.out.println("登錄失敗");}}public static boolean login(String username, String password){if(username == null || password == null){return false;}Connection connection = null;PreparedStatement preparedStatement = null;ResultSet resultSet = null;try {connection = JdbcUtil.getConnection();//注意參數兩端都有單引號 因為他們是字符串String sql = "select * from user where username= ? and password= ? ";preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1,username);preparedStatement.setString(2,password);resultSet = preparedStatement.executeQuery();return resultSet.next();} catch (SQLException e) {e.printStackTrace();}finally {JdbcUtil.close(preparedStatement,connection,resultSet);}return false;} }

    3 JDBC控制事務-轉賬案例

    使用Connection對象來管理事務
    執行操作之前開事務 置為false
    事務結束之后提交事務
    在catch里面回滾 catch捕獲的異常范圍要擴大 不能僅僅時sql異常

    package jdbc;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;public class JdbcDemo4 {public static void main(String[] args) {Connection conn = null;PreparedStatement pstmt1 = null;PreparedStatement pstmt2 = null;try{conn = JdbcUtil.getConnection();conn.setAutoCommit(false);String sql1 = "update account set balance = balance - ? where id = ?";String sql2 = "update account set balance = balance + ? where id = ?";pstmt1 = conn.prepareStatement(sql1);pstmt2 = conn.prepareStatement(sql2);pstmt1.setDouble(1,500);pstmt2.setDouble(1,500);pstmt1.setInt(2,2);pstmt2.setInt(2,1);pstmt1.executeUpdate();pstmt2.executeUpdate();conn.commit();}catch(Exception e){//任何異常都要回滾 所有這里不只是sql異常try {if(conn != null) conn.rollback();} catch (SQLException ex) {ex.printStackTrace();}e.printStackTrace();}finally {if(pstmt2!=null){try {pstmt2.close();} catch (SQLException e) {e.printStackTrace();}}JdbcUtil.close(pstmt1,conn);}} }

    總結

    以上是生活随笔為你收集整理的【JavaWeb】JDBC的基本操作和事务控制+登录和转账案例的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。