11、JDBC连接数据的步骤

1、JDBC连接数据库的步骤

Class.forName("com.jdbc.mysql.Driver");
String url="jdbc:mysql://localhost:3306/fresh";
Connection con=DriverManager.getConnection(url,"root","root");

2、具体实现增删改查的操作

PreparedStatement ps=null;
Connection cn=null;
ResultSet rs=null;

Class.forName(“com.jdbc.mysql.Driver”);
String url=”jdbc:mysql://localhost:3306/fresh”;
Connection con=DriverManager.getConnection(url,”root”,”root”);

//实现添加操作

String sql="insert into Student values(?,?,?);
ps=ct.prepareStatement(sql);
ps.setInt(1,12);   ps.setString(2,"小明");   ps.setString("伙夫");
// i表示用来接收改动的行数
int i=ps.executeUpdate();  

if(i==1){
System.out.println("添加成功!");
}else{
System.out.println("添加失败!");
}

实现删除操作,代码如下:

String sql="delete from Student where id=?;
ps=ct.prepareStatement(sql);
ps.setInt(1,12); 
// i表示用来接收改动的行数
int i=ps.executeUpdate();  

if(i==1){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}

实现修改操作,代码如下:

String sql="update Student set name=”小明“ where id=?;
ps=ct.prepareStatement(sql);
ps.setInt(1,12);
// i表示用来接收改动的行数
int i=ps.executeUpdate();  

if(i==1){
System.out.println("修改成功!");
}else{
System.out.println("修改失败!");
}

实现查找操作

String sql="select  * from Student where id=?;
ps=ct.prepareStatement(sql);
ps.setInt(1,12); 
// rs表示查询到的数据列表
ResultSet  rs=ps.executeQuery();  
while(rs.next()){
        int id=rs.setString(1);
        String name=rs.setString(2);
        System.out.println(id+" "+name); 
}

猜你喜欢

转载自blog.csdn.net/nba_linshuhao/article/details/82625366
今日推荐