1.首先在可视化数据库中创建表student
2.在表中添加一些数据
手动输入数据
3.使用配置了mysql5驱动包的jdbc技术
创建一个学生类
public class Student {
String name;
int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
创建一个测试类
在类中查询,关闭连接、对象、结果集,将查询的数据封装进对象集合,传参,可以设置一个方法封装代码传参,我在这里省略了。
package com.demo.test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestJdbc3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
//1.配置驱动--我的另一篇文章写过
try {
//2.加载驱动 mysql5
Class.forName("com.mysql.jdbc.Driver");//jdbc4及以上可以不写,也就是jdk1.5以上
//3.创建连接数据库的url
String url = "jdbc:mysql://127.0.0.1:3306/mytest?useUnicode = true & CharacterEncoding = UTF-8";
//连接数据库的username
String username = "root";
//连接数据库的password
String password = "root";
//4.连接数据库
conn = DriverManager.getConnection(url,username,password);
//5.测试连接是否成功
//System.out.println(conn);
//6.sql查询
System.out.println("请输入要查询的学生名字:");
String name = scan.next();
System.out.println("请输入要查询的学生id");
int id = scan.nextInt();
String sql = "select * from student where name = '"+name+"'and id = " + id;
//7.创建操作数据库的对象
pstmt = conn.prepareStatement(sql);
//8.执行查询
rs = pstmt.executeQuery();
System.out.println("id\t\t名字");
List<Student> studentList = new ArrayList<>();
//封装到集合
while(rs.next()){
int idno = rs.getInt("id");
String sname = rs.getString("name");//可以通过列名和列列所在的字段2进行获取
Student student = new Student();
student.setId(idno);
student.setName(sname);
studentList.add(student);//循环封装所有的行
}
for (Student student : studentList) {
System.out.println(student.toString());
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {//以下三个安装先后顺序
if(rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(pstmt != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
最终的测试结果