java web 串連mysql

來源:互聯網
上載者:User

標籤:

 

1.建立資料庫

 1 create database jdbc; 

 

2.建立資料表

1 create table create table stu10( id int(10) primary key auto_increment, name varchar(20) not null, age varchar(10) not null, address varchar(20) not null);

 

3.通過insert語句增加資料

1 insert into stu10 values(1,‘碼-奴‘,‘20‘,‘浙江嘉興‘);

 4.建立串連資料庫類

 1 package com.tu.jdbc; 2  3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6  7 public class Jdbc_con { 8     public Connection getConnection(){ 9         try {10             //載入資料庫驅動11             Class.forName("com.mysql.jdbc.Driver");12             //串連資料庫13             return DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","123");14         } catch (Exception e) {15             // TODO Auto-generated catch block16             e.printStackTrace();17         }18         return null;19     }20     21     public void closeConection(Connection con){22         if(con!=null){23             try {24                 con.close();25             } catch (SQLException e) {26                 // TODO Auto-generated catch block27                 e.printStackTrace();28             }29         }30     }31 }

5.建立測試類別

 1 package com.tu.jdbc; 2  3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7  8 public class Test { 9 10     public static void main(String[] args) {11         Test ts = new Test();12         ts.list();13 14     }15 16     public void list() {17         Jdbc_con jc = new Jdbc_con();18         Connection jdbc = jc.getConnection();19         String sql = "select id,name from stu10";20         try {21             Statement sm = jdbc.createStatement();22             ResultSet rs = sm.executeQuery(sql);23             while (rs.next()) {24                 int id = rs.getInt(1);25                 String name = rs.getString(2);26                 System.out.println(id + name);27             }28         } catch (SQLException e) {29             // TODO Auto-generated catch block30             e.printStackTrace();31         }32 33     }34 }

 

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