第一步:新建数据表:
------------------------------------------------------------------------------------------------------------
use eshop1;
create table c_goods(
ccode int primary key,
cname varchar(200)
);
添加数据
insert into c_goods(ccode,cname) values(1000,'图书'),(1001,'服装'),(1002,'家居'),(1003,'数码');
------------------------------------------------------------------------------------------------------------
use eshop1;
create table p_goods(
pcode int,
pname varchar(200),
psorts int
);
添加数据
insert into p_goods(pcode,pname,psorts) values(1,'页数',1000),(2,'作者',1000),(3,'品牌',1001),(4,'材质',1002),(5,'续航时间',1003);
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
第二步:添加
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
第三步:JDBC代码:
1 package day_3; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 public class ShowGoodNameAndPrice { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 /* 14 * 1.加载驱动程序,因为应用当中,可能存在多个 15 * 数据库产品的驱动程序(多个jar) 16 */ 17 try { 18 Class.forName("com.mysql.jdbc.Driver"); 19 } catch (ClassNotFoundException e) { 20 // TODO Auto-generated catch block 21 e.printStackTrace(); 22 } 23 /** 24 * 2.建立数据库连接 25 * 26 */ 27 String user ="root"; 28 String password="123456"; 29 String url="jdbc:mysql://localhost:3306/eshop1"; 30 Connection con=null; 31 try { 32 con=DriverManager.getConnection(url, user, password); 33 /*** 34 * 3.执行sql语句, 35 * 与数据库服务器进行通信 *Statement接口对象 36 */ 37 String sql=" select *from c_goods c join p_goods p on c.ccode=p.psorts;"; 38 Statement stmt=con.createStatement(); 39 /**** 40 * 4.得到结果,处理业务逻辑 41 */ 42 ResultSet rs=stmt.executeQuery(sql); 43 while(rs.next()){ 44 45 String cname=rs.getString("cname"); 46 double ccode=rs.getDouble("ccode"); 47 48 String pname = rs.getString("pname"); 49 int pcode = rs.getInt("pcode"); 50 int psorts = rs.getInt("psorts"); 51 52 System.out.println("商品列表"); 53 System.out.println( "编号:" +ccode+" 商品类型:"+cname ); 54 System.out.println( "商品参数表" ); 55 System.out.println( "编号:" +pcode+" 参数名称:"+pname+" 参数所属分类:"+ psorts ); 56 System.out.println(); 57 } 58 } catch (SQLException e) { 59 // TODO Auto-generated catch block 60 e.printStackTrace(); 61 }finally{ 62 try { 63 con.close(); 64 } catch (SQLException e) { 65 // TODO Auto-generated catch block 66 e.printStackTrace(); 67 } 68 } 69 70 } 71 72 }