首页 > 代码库 > JDBC连接mysql
JDBC连接mysql
第一步:新建数据表:
------------------------------------------------------------------------------------------------------------
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代码:
package day_3;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ShowGoodNameAndPrice {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 1.加载驱动程序,因为应用当中,可能存在多个
* 数据库产品的驱动程序(多个jar)
*/
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 2.建立数据库连接
*
*/
String user ="root";
String password="123456";
String url="jdbc:mysql://localhost:3306/eshop1";
Connection con=null;
try {
con=DriverManager.getConnection(url, user, password);
/***
* 3.执行sql语句,
* 与数据库服务器进行通信 *Statement接口对象
*/
String sql=" select *from c_goods c join p_goods p on c.ccode=p.psorts;";
Statement stmt=con.createStatement();
/****
* 4.得到结果,处理业务逻辑
*/
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
String cname=rs.getString("cname");
double ccode=rs.getDouble("ccode");
String pname = rs.getString("pname");
int pcode = rs.getInt("pcode");
int psorts = rs.getInt("psorts");
System.out.println("商品列表");
System.out.println( "编号:" +ccode+" 商品类型:"+cname );
System.out.println( "商品参数表" );
System.out.println( "编号:" +pcode+" 参数名称:"+pname+" 参数所属分类:"+ psorts );
System.out.println();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
JDBC连接mysql