jdbc連結資料庫mysql

來源:互聯網
上載者:User

標籤:

package cn.itcast.demo2;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import org.junit.Test;public class Demo2 {    /*     * 串連資料庫,得到Connection就算成功!     * 對資料庫做增、刪、改     */    @Test    public void fun1() throws ClassNotFoundException, SQLException {        /*         * 一、得到Connection         * 1. 準備四大參數         * 2. 載入驅動類         * 3. 得到Connection         */        // 準備四大參數        String driverClassName = "com.mysql.jdbc.Driver";        // jdbc協議的格式!jdbc:工商的名稱:子協議(由工商自己來規定)        // 對mysql而言,它的子協議結構://主機:連接埠號碼/資料庫名稱        String url = "jdbc:mysql://localhost:3306/mydb3";        String username = "root";        String password = "123";                // 載入驅動類        Class.forName(driverClassName);        // 使用DriverManager,以及省下的3個參數,得到Connection        Connection con = DriverManager.getConnection(url, username, password);                /*         * 二、對資料庫做增、刪、改         * 1. 通過Connection對象建立Statement         * > Statement語句的發送器,它的功能就是向資料庫發送sql語句!         * 2. 調用它的int executeUpdate(String sql),它可以發送DML、DDL         */        // 1. 通過Connection得到Statement對象        Statement stmt = con.createStatement();        // 2. 使用Statement發送sql語句!//        String sql = "INSERT INTO stu VALUES(‘ITCAST_0003‘, ‘wangWu‘, 88, ‘male‘)";//        String sql = "UPDATE stu SET name=‘zhaoLiu‘, age=22, " +//                "gender=‘female‘ WHERE number=‘ITCAST_0003‘";        String sql = "DELETE FROM stu";        int r = stmt.executeUpdate(sql);        System.out.println(r);    }        /**     * 執行查詢     * @throws ClassNotFoundException      * @throws SQLException      */    @Test    public void fun2() throws ClassNotFoundException, SQLException {        /*         * 一、得到Connection         * 二、得到Statement,發送select語句         * 三、對查詢返回的“表格”進行解析!         */        /*         * 一、得到串連         * 1. 準備四大串連參數         */        String driverClassName = "com.mysql.jdbc.Driver";        String url = "jdbc:mysql://localhost:3306/exam";        String username = "root";        String password = "123";                /*         * 2. 載入驅動類         */        Class.forName(driverClassName);        /*         * 3. 通過省下的三個參數調用DriverManger的getConnection(),得到串連         */        Connection con = DriverManager.getConnection(url, username, password);                /*         * 二、得到Statement,執行select語句         * 1. 得到Statement對象:Connection的createStatement()方法         */        Statement stmt = con.createStatement();        /*         * 2. 調用Statement的ResultSet rs = executeQuery(String querySql)         */        ResultSet rs = stmt.executeQuery("select * from emp");                /*         * 三、解析ResultSet         * 1. 把行游標移動到第一行,可以調用next()方法完成!         */        while(rs.next()) {//把游標向下移動一行,並判斷下一行是否存在!            int empno = rs.getInt(1);//通過列編號來擷取該列的值!            String ename = rs.getString("ename");//通過列名稱來擷取該列的值            double sal = rs.getDouble("sal");                        System.out.println(empno +  ", " + ename + ", " + sal);        }                /*         * 四、關閉資源         * 倒關         */        rs.close();        stmt.close();        con.close();//這個東東,必須要關,不關就死!    }        // 正常化    @Test    public void fun3() throws Exception {        Connection con = null;//定義引用        Statement stmt = null;        ResultSet rs = null;        try {            /*             * 一、得到串連             */            String driverClassName = "com.mysql.jdbc.Driver";            String url = "jdbc:mysql://localhost:3306/exam";            String username = "root";            String password = "123";                        Class.forName(driverClassName);            con = DriverManager.getConnection(url, username, password);//執行個體化                        /*             * 二、建立Statement             */            stmt = con.createStatement();            String sql = "select * from emp";            rs = stmt.executeQuery(sql);                        rs.last();//把游標移動到最後一行System.out.println(rs.getRow());            rs.beforeFirst();                        /*             * 三、迴圈遍曆rs,列印其中資料             *              * getString()和getObject()是通用的!             *///            while(rs.next()) {//                System.out.println(rs.getObject(1) + ", " //                        + rs.getString("ename") + ", " + rs.getDouble("sal"));//            }                        int count = rs.getMetaData().getColumnCount();            while(rs.next()) {//遍曆行                for(int i = 1; i <= count; i++) {//遍曆列                    System.out.print(rs.getString(i));                    if(i < count) {                        System.out.print(", ");                    }                }                System.out.println();            }                    } catch(Exception e) {            throw new RuntimeException(e);        } finally {            // 關閉            if(rs != null) rs.close();            if(stmt != null) stmt.close();            if(con != null) con.close();        }            }}

 

jdbc連結資料庫mysql

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.