java串連mysql資料庫

來源:互聯網
上載者:User

標籤:

1、首先下載mysql安裝包,下載連結mysql下載,然後安裝。

2、輸入安裝時的使用者名稱和密碼,串連資料庫。

3、在Eclipse 中安裝mysq JDBCl驅動,安裝步驟如示:







測試是否成功串連mql,代碼:

package day_09;import java.sql.*;public class Test{public static void main(String[] args) { String url="jdbc:mysql://localhost:3306/mydb";       String user="root";       String password="281889";      Connection conn=null;            Statement stmt=null;           ResultSet rs=null;     try     {Class.forName("com.mysql.jdbc.Driver");        conn=DriverManager.getConnection(url,user,password);          stmt=conn.createStatement();          String sql;        sql="insert into student values(2014218,'李月','女')";        stmt.execute(sql);         sql="select * from student";          rs = stmt.executeQuery(sql);            System.out.println("學號" + "\t\t\t" + " 姓名"+"\t\t\t"+"性別");           String name = null;            while(rs.next())        {                name = rs.getString("sname");              System.out.println(rs.getString("sno") + "\t\t\t" + name+"\t\t\t"+rs.getString("sex"));          }         }     catch(ClassNotFoundException e1)           {               System.out.println("資料庫驅動不存在!"+e1.toString());           }           catch(SQLException e2)           {               System.out.println("資料庫存在異常"+e2.toString());           }           finally           {               try               {                   if(rs!=null)                       rs.close();                   if(stmt!=null)                       stmt.close();                   if(conn!=null)                       conn.close();               }               catch(SQLException e)               {                   System.out.println(e.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.