java串連mysql資料庫的方法

來源:互聯網
上載者:User

標籤:java   mysql   

用java連資料庫的有點之一就是不用去設定檔,直接引入一個jar包就行,這也是和php是不同的,但是具體的對於資料庫的操作是相對php有一些複雜的,主要要做的步奏如下:
1:引入jar包和sql包。
2:載入資料庫驅動,
3:設定,串連,查詢,執行
4:按步驟去執行。
5:取回結果
代碼如下:

package com_jdbc_1;import java.sql.*;import javax.sql.*;public class demon_1 {    /**     * @param args     */    public static void main(String[] args) throws Exception {//      定義一個串連        Connection ct=null;//      定義查詢條件        PreparedStatement ps=null;//      定義結果集        ResultSet rs=null;//      選擇資料庫驅動        Class.forName("com.mysql.jdbc.Driver");//      設定串連資訊        ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","toor");//      設定查詢        ps=ct.prepareStatement("select * from testuser");//      執行並得到結果集        rs=ps.executeQuery();        int i=0;//      遍曆輸出        while(rs.next()){            System.out.println(rs.getInt(1)+" "+rs.getString("username"));        }    }}

java串連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.