1. 程式人生 > 資料庫 >JAVA使用JDBC連線MySql資料庫

JAVA使用JDBC連線MySql資料庫

前言

 JDBC(Java Database Connectivity)提供了一種與平臺無關的用於執行SQL語句的標準Java API,可以方便地實現多種關係型資料庫的統一操作,它由一組用Java語言編寫的介面和類組成。

 

//test資料庫   customers表新增一條記錄     
public class jdbcdemo {

    public  static  void main(String [] args)  {
        Connection con=null;
        Statement statement=null;
        try {
            //1.註冊驅動
            Class.forName("com.mysql.jdbc.Driver");

            //2.定義SQL語句      進行增刪改查的一些操作
            String sql="insert into customers values(19,'詹先生',null ,null,null)";

            //3.獲取資料庫的連線物件                                     test是我自己的資料庫名字         mysql賬號和密碼
             con= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","Zjh520.1314.");

            //4.獲取sql的物件   Statement
            statement=con.createStatement();

            //5.執行sql
            int finish=statement.executeUpdate(sql); //返回結果是影響的行數

            //6.處理結果
            System.out.println(finish);
            if (finish>0){
                System.out.println("執行成功");

            }else {
                System.out.println("執行失敗");

            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //在這裡釋放資源    標準寫法
            try {
                //避免空指標異常
                if (statement!=null){
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }


            try {
                if (con!=null) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }

}