1. 程式人生 > >Android JDBC簡單使用

Android JDBC簡單使用

一,JDBC 簡介

JDBC:java database connectivity java資料庫連線

常用的資料庫mysql oracle sqlserver

sun公司提供了一套jdbc的介面,讓資料庫廠商實現。

 

二,JDBC使用:

1,JDBC簡單使用

    步驟:

       1),匯入jar包   

public class JDBCTest {

 

   @Test

   public void jdbcTest() {

       try {

          // [1]註冊mysql驅動

           //DriverManager.registerDriver(new Driver());    

           Class.forName("com.mysql.jdbc.Driver");

           

           // [2]連線資料庫

           // jdbc:subprotocol:subname

           //  URL 固定格式: jdbc:資料庫名字// localhost:3306/ lol (本地資料庫地址),使用者名稱,密碼

           Connection connection = DriverManager.getConnection(

                   "jdbc:mysql://localhost:3306/lol", "root", "1q2w3e");

 

          // [3]建立一個statement物件 類似 庫管

           Statement statement = connection.createStatement();

           // [4]執行查詢語句

           ResultSet resultSet = statement.executeQuery("select * from student");

           resultSet.next();

           String name = resultSet.getString(2);

           System.out.println("name = "+name);

           

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

   }

}

2,JDBC類重要的方法:

    【1】DriverManager:註冊驅動 告訴當前程式 連線哪個資料庫       

            DriverManager.registerDriver(new Driver());

            Class.forName("com.mysql.jdbc.Driver");

            獲取連線 :“ DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "1q2w3e");

    【2】Connection: 連線資料庫的物件

            獲取一個statement                connection.createStatement()

            獲取一個preparedStatement

    【3】Statement: 用來執行sql語句 是一個庫管物件

            介面 Statement:用於執行靜態 SQL 語句並返回它所生成結果的物件。

            方法:

                executeQuery(String sql)    執行給定的 SQL 語句,該語句返回單個 ResultSet 物件。

    【4】ResultSet: 結果集物件 裡面有一個游標 預設在第一行之前 呼叫next方法 就可以向下移動

            介面 ResultSet: 表示資料庫結果集的資料表,通常通過執行查詢資料庫的語句生成。

            方法:getString(String columnLabel)   以 Java 程式語言中 String 的形式獲取此 ResultSet 物件的當前行中指定列的值。

                      executeUpdate(String sql) 執行給定 SQL 語句,該語句可能為 INSERT、UPDATE 或 DELETE 語句,或者不返回任何內容的 SQL 語句(如 SQL DDL 語句)。

 

    為什麼使用     Class.forName("com.mysql.jdbc.Driver");建立物件:

    // 本身方法也是new Driver。我們用Class去呼叫免得重複建立物件 Driver 類裡自己靜態程式碼塊進行載入了自己

 

3,JDBC簡單呼叫增刪改查:

 

public class JDBCSample {

 

    @Test

    public void add() {

        //插入語句

        try {

            //註冊驅動

            Class.forName("com.mysql.jdbc.Driver");

            //連結資料庫

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/lol", "root", "1q2w3e");

            //申請物件類似於庫管

            Statement statement = connection.createStatement();

            

            int result = statement

                    .executeUpdate("insert into student values(30,'zhaoyun',99,100)");

            if (result > 0) {

                System.out.println("插入成功");

            } else {

                System.out.println("插入失敗");

            }

 

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

 

    @Test

    public void remove() {

        //刪除語句

        try {

            Class.forName("com.mysql.jdbc.Driver");

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/lol", "root", "1q2w3e");

            Statement statement = connection.createStatement();

            int result = statement

                    .executeUpdate("delete from student where id > 20");

            if (result > 0) {

                System.out.println("刪除成功" + result);

            } else {

                System.out.println("刪除失敗" + result);

            }

 

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

 

    @Test

    public void update() {

        //更新語句

        try {

            Class.forName("com.mysql.jdbc.Driver");

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/lol", "root", "1q2w3e");

            Statement statement = connection.createStatement();

 

            int result = statement

                    .executeUpdate("update student set english = 100 where id = 30");

            if (result > 0) {

                System.out.println("更新成功" + result);

            } else {

                System.out.println("更新失敗" + result);

            }

 

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

 

    }

 

    @Test

    public void query() {

        //查詢語句

        try {

            Class.forName("com.mysql.jdbc.Driver");

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/lol", "root", "1q2w3e");

            Statement statement = connection.createStatement();

            ResultSet resultSet = statement

                    .executeQuery("select * from student");

 

            while (resultSet.next()) {

                String id = resultSet.getString(1);

                String name = resultSet.getString(2);

                String english = resultSet.getString(3);

                String math = resultSet.getString(4);

                

                System.out.println("id = "+id +" name = "+name + " english = "+english +" math = "+math);

            }

 

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

}

 

 

4,JDBC的封裝:

    [1]建立配置檔案:db.properties 存放路徑,帳號,密碼。

className:com.mysql.jdbc.Driver

url:jdbc:mysql://localhost:3306/lol

name:root

pwd:1q2w3e

    [2] 建立Utils getConnection獲取對資料庫的連結

public class JDBCUtils {

 

    private static String className;

    private static String url;

    private static String name;

    private static String pwd;

 

    static {

        try {

            //儲存本地配置

            Properties properties = new Properties();

            properties.load(new FileInputStream("db.properties"));

            //獲取properties 中的欄位

            className = properties.getProperty("className");

            url = properties.getProperty("url");

            name = properties.getProperty("name");

            pwd = properties.getProperty("pwd");

 

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    //獲取

    public static Connection getConnection() throws Exception {

        Class.forName(className);

        return DriverManager.getConnection(url, name, pwd);

    }

}

    [3] 寫SQL語句

public class JDBCUtilsTest {

 

    @Test

    public void add() {

        try {

            Connection connection = JDBCUtils.getConnection();

            Statement statement = connection.createStatement();

            int result = statement.executeUpdate("insert into student values(30,'machao',99,99)");

            System.out.println("result = "+result);

            

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        };

    }

 

    @Test

    public void remove() {

        try {

            Connection connection = JDBCUtils.getConnection();

            Statement statement = connection.createStatement();

            int result = statement.executeUpdate("delete from student where id = 30");

            System.out.println("result = "+result);

            

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        };

    }

 

    @Test

    public void update() {

        try {

            Connection connection = JDBCUtils.getConnection();

            Statement statement = connection.createStatement();

            int result = statement.executeUpdate("update student set english = 100 where id =20");

            System.out.println("result = "+result);

            

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        };

        

    }

 

    @Test

    public void query() {

        try {

            Connection connection = JDBCUtils.getConnection();

            Statement statement = connection.createStatement();

            

            ResultSet resultSet = statement.executeQuery("select * from student");

            

            while(resultSet.next()){

                String id = resultSet.getString(1);

                String name = resultSet.getString(2);

                String english = resultSet.getString(3);

                String math = resultSet.getString(4);

                System.out.println("id = "+id +" name = "+name + " english = "+english  +" math = "+math);

            }

            

            

            

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        

    }

}

 

5,login登陸查詢資料庫

 

    *BUG,預編譯。佔位符。進行編譯轉義。