你的位置:首页 > Java教程

[Java教程]java web 连接mysql


 

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 }