import java.sql.*;
import java.util.Scanner;
/**
* @author zzw
* @create 2020/11/14-14:41
*/
public class jdbcTest08 {
public static void main(String[] args) {
/*
我们使用预编译的方式,
报错 check the manual that corresponds to your MySQL server version for the right syntax to use near ''desc'' at line 1
这里我们使用了sql语句的拼接,但是由于是编译后才进行的拼接,所以会报错,这个时候我们只能使用Statement类,而不是PrearedStatement。
**我觉得Statement类就是给了在需要用户点击或者输入后数据发生变化的时候使用
**PrearedStatement类就是用户在进行登录等关键操作的时候使用?
//用户在控制台输入desc就是降序,输入asc就是升序
Scanner s = new Scanner(System.in);
System.out.println("请输入desc或asc");
System.out.print("请输入:");
String keyWords = s.nextLine();
//jdbc6步走
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1、注册驱动
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "a");
//3、获取数据库操作对象
String sql = "select 语文 from jdbc01 order by 语文 ?"; //?是一个desc或者asc
ps = conn.prepareStatement(sql);
//编译之后给占位符赋值
ps.setString(1, keyWords);
//4、执行sql
rs = ps.executeQuery();
//遍历结果集 rs.next()有数据就进行取值
while (rs.next()) {
System.out.println(rs.getString("语文"));
}
//5、处理查询结果集
} catch (SQLException e) {
e.printStackTrace();
} finally {
//6、释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
*/
//我们使用Statement来进行字符串拼接,根据用户输入对数据进行变化
//用户在控制台输入desc就是降序,输入asc就是升序
Scanner s = new Scanner(System.in);
System.out.println("请输入desc或asc");
System.out.print("请输入:");
String keyWords = s.nextLine();
//jdbc6步走
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1、注册驱动
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "a");
//3、获取数据库操作对象
stmt = conn.createStatement();
//4、执行sql
String sql = "select 语文 from jdbc01 order by 语文 " + keyWords;
rs = stmt.executeQuery(sql);
//遍历结果集 rs.next()有数据就进行取值
while (rs.next()) {
System.out.println(rs.getString("语文"));
}
//5、处理查询结果集
} catch (SQLException e) {
e.printStackTrace();
} finally {
//6、释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
JDBC学习----08--演示Statement用途(升序降序)
最新推荐文章于 2023-02-12 22:56:24 发布