首先需要打印出来,所以我们先创建一个类,用来对应数据库中的值并且输出。
public class User {
private Integer id;
private String name;
private int age;
private int teacherId;
public int getTeacherId() {
return teacherId;
}
public void setTeacherId(int teacherId) {
this.teacherId = teacherId;
}
public User(Integer id, String name, int age,int teacherId) {
this.id = id;
this.name = name;
this.age = age;
this.teacherId=teacherId;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
", age=" + age +
", teacherId=" + teacherId +
‘}‘;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
调用类中需要有七个步骤
1连接数据库
2.编写?sql
3.预编译
4.填充占位符
5.执行
6判断是否有值,然后打印
7.关闭
package cn.kgc.conn.Hello;
import cn.kgc.conn.Hello.User;
import cn.kgc.conn.Hello.jdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by helloworld on 2020/6/24.
* 根据id查询一个数据
*/
public class select {
public static void main(String[] args){
Connection connection=null;
PreparedStatement pstm=null;
ResultSet rs=null;
//1连接数据库
try {
connection = jdbcUtil.getConnection();
//2.编写?sql
String sql ="SELECT * FROM student where Id =?";
//3.预编译
pstm = connection.prepareStatement(sql);
//4.填充占位符
pstm.setObject(1,"2");
//5.执行
rs = pstm.executeQuery();
//6判断是否有值,然后打印
if(rs.next()){
/*int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
*/
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
int teacherId =rs.getInt("teacherId");
User user = new User(id,name,age,teacherId);
System.out.println(user.toString());
// System.out.println("id:"+id+",name:"+name+",age"+age);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//7.关闭
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}