idea連接數據庫進行查找


首先需要打印出來,所以我們先創建一個類,用來對應數據庫中的值並且輸出。

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();
}


}
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM