jdbc简单的条件查询案例
表内容如下 两个字段 qq和phone
通过qq字段查询对应的phone字段 代码如下
package com.test.jdbc;
import java.sql.*;
import java.util.Scanner;
public class SqlDemo {
//类加载
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/qq_sj","root","liuhaisen");
//创建Statement对象
Statement statement = con.createStatement();
//执行sql语句 用户输入qq字段数据 查询对应的phone字段
Scanner scanner = new Scanner(System.in);
System.out.println("请输入qq号");
String qq = scanner.nextLine();
String sql = "select phone from sj where qq = '"+qq+"'";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String phone = resultSet.getString("phone");
System.out.println("您的手机号是"+phone);
}
//关闭资源
resultSet.close();
statement.close();
con.close();
}
}
运行结果如下