java串連MySql資料庫

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   os   sp   java   for   

1.首先安裝MySql

2.其次方便操作mysql應該下載一個圖形介面的資料庫操作軟體:例如 mysql-front 或者 EMS Sql manager

3.安裝ems時會提示設定root使用者的密碼,這個密碼在以後串連資料庫時會用的到。例如設定為 "126456"

4.其次想通過編譯包含資料庫操作的函數要在Jcreator中包含 mysql.jar 
                            "配置"-"選項"-"JDK設定檔"-"JDK版本"-編輯-"添加存檔",選擇mysql.jar。

 

資料庫的操作無法包含兩個方面:載入驅動 + 擷取Connection對象,然後一切的操作都建立在Connection對象之上的。一下給出串連mysql的資料庫的詳細步驟:

 

import java.sql.*;

public class rr
{
  public static void main(String[] args)
  {
    try
    {
      String url="jdbc:mysql://localhost/mydb";
      String user="root";
      String pwd="123456";
      
      //載入驅動,這一句也可寫為:Class.forName("com.mysql.jdbc.Driver");
     Class.forName("com.mysql.jdbc.Driver").newInstance();
      //建立到MySQL的串連
       Connection conn = DriverManager.getConnection(url,user, pwd);
      
      //執行SQL語句
       Statement stmt = conn.createStatement();//建立語句對象,用以執行sql語言
      ResultSet rs = stmt.executeQuery("select * from student");
     
       //處理結果集
      while (rs.next())
      {
        String name = rs.getString("name");
        System.out.println(name);
      }
      rs.close();//關閉資料庫
      conn.close();
    }
    catch (Exception ex)
    {
      System.out.println("Error : " + ex.toString());
    }
  }
}

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.