java鏈接MySQL數據庫(jdbc)

package zp.itcase.JDBCdemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo3 {
    public static void main(String[] args) {
        Statement stmt = null;
        Connection conn = null;
        try {
            // 1.註冊驅動
            Class.forName("com.mysql.jdbc.Driver");
            // 2.獲取鏈接對象
            conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");
            // 3. 定義sql
            String sql = "update account set balance = 1500 where id =3";
            // 4.獲取執行sql的對象
            stmt = conn.createStatement();
            // 5.執行sql
            int count = stmt.executeUpdate(sql);
            // 6.處理結果
            if (count > 0) {
                System.out.println("修改爲功");
            } else {
                System.out.println("修改失敗");
            }


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
相關文章
相關標籤/搜索