Java資料庫編程(JDBC)

來源:互聯網
上載者:User

標籤:std   code   .sql   cte   自己   each   編碼   stat   exec   

一.使用Java對資料庫的操作步驟:

  1.根據應用程式的資料庫類型,載入相應的驅動;

  2.串連到資料庫,得到Connection對象;

  3.通過Connection建立Statement對象;

  4.使用Statement對象提交SQL語句;

  5.操作結果集

  6.回收資料庫資源

  7.關閉串連

package com.lovo.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;public class JdbcTestDML {    public static void main(String[] args) {        //資料庫操作步驟:        //1、載入驅動——告訴驅動管理器我們將使用哪一個資料庫的驅動包        try {            //url——統一資源定位器----樣式:  協議://ip地址:連接埠號碼/服務            Class.forName("com.mysql.jdbc.Driver");        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        //2、操作JDBC API完成資料庫動作        //①、擷取串連        Connection con = null;        try {            //?useSSL=false——是指不顯示安全警告,?useUnicode=true&characterEncoding=utf8——出現亂碼時改成自己一致的編碼如utf-8d的            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test134?useSSL=false", "root", "13405");            //②-1、書寫SQL語句------字串拼接、            //增加            //String sql="INSERT INTO t_class (f_classname,f_teacher) VALUES (‘j22‘,‘彎彎‘)";            //更改            String sql="UPDATE t_class SET f_classname =‘j66‘,f_teacher=‘極低‘ WHERE pk_classsid =4";            //②-2、擷取語句對象-----statement對像            Statement state =con.createStatement();            //②-3、執行語句對象------所有的DML語句,全部執行executeUpdate()方法            int row=state.executeUpdate(sql);        } catch (SQLException e) {            e.printStackTrace();        }finally {            //③、關閉串連            if(con!=null){                try {                    con.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }        }    }}

 上面這個例子用的是DML語句只有增刪改,因此沒有結果集的返回,當使用DQL語句做查詢時,就會有結果集的出現和使用。

Java資料庫編程(JDBC)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.