Java串連mysql資料庫

來源:互聯網
上載者:User

標籤:pst   連接埠   int   uil   pass   main   catch   年齡   col   

工具:eclipse

   MySQL5.6

   MySQL串連驅動:mysql-connector-java-5.1.27.jar

載入驅動:

  1. 在工程目錄中建立lib檔案夾,將下載好的JDBC(jar包)放到該檔案夾下,如所示:

2. 右鍵工程名,在java build path中的Libraries分頁中選擇Add JARs...,選擇剛才添加的JDBC,如:

資料包準備:

資料:

串連資料庫並讀取資料:

  資料庫名稱:stu

  資料包名稱:student

  連接埠號碼:3306

  使用者名稱:root

  密碼:123456

package com.oracle.zibo;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Calendar;public class Demo1 {    public static final String url="jdbc:mysql://127.0.0.1:3306/stu"; //URL指向要訪問的資料庫名    public static final String name="com.mysql.jdbc.Driver";//驅動程式名    public static final String user="root";//MySQL配置時的使用者名稱    public static final String password="123456";//MySQL配置時的密碼        public static void main(String[] args) {        //遍曆查詢結果集        try{            Class.forName(name);//載入驅動程式            //1.getConnection()方法,串連MySQL資料庫!!            Connection conn=DriverManager.getConnection(url, user, password);            if(!conn.isClosed())            System.out.println("Succeeded connecting to the Database!");            //2.要執行的SQL語句            String sql="select student_no,student_name,birthday from student";            //建立statement類對象,用來執行SQL語句!!            PreparedStatement pst=conn.prepareStatement(sql);            //3.ResultSet類,用來存放擷取的結果集!!            ResultSet resultSet=pst.executeQuery();                        while(resultSet.next()){                //擷取student_no這列資料                String studentNo=resultSet.getString("student_no");                //擷取student_name這列資料                String studentName=resultSet.getString("student_name");                //此處匯入Calendar類用來計算學生的年齡                int year=Calendar.getInstance().getTime().getYear();                int age=year-resultSet.getDate("birthday").getYear();                //輸出結果                System.out.println("學生編號"+studentNo+",學生姓名:"+studentName+",年齡:"+age);            }                        pst.close();            conn.close();            //處理異常        }catch(Exception e){            e.printStackTrace();        }    }}

運行結果:

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.