1 Star 0 Fork 0

曾铖坚 / day24-code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
JDBCTest8.java 3.51 KB
一键复制 编辑 原始数据 按行查看 历史
package com.bjpowernode.jdbc;
import java.sql.*;
import java.util.Scanner;
public class JDBCTest8 {
public static void main(String[] args) {
//必须用Statement的场景
// 用户在控制台输入desc就是降序,输入asc就是升序
/*System.out.println("输入desc或者asc,desc代表降序,asc代表升序");
System.out.print("请输入:");
Scanner sc = new Scanner(System.in);
String keyWords = sc.nextLine();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bjpowernode","root","246810");
//3.获取预编译数据库操作对象
String sql = "select ename from emp order by ename ?";
ps = conn.prepareStatement(sql);
ps.setString(1,keyWords);
//4.执行sql
rs = ps.executeQuery();
//5.处理查询结果集
while (rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (Exception 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();
}
}
}*/
System.out.println("输入desc或者asc,desc代表降序,asc代表升序");
System.out.print("请输入:");
Scanner sc = new Scanner(System.in);
String keyWords = sc.nextLine();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bjpowernode", "root", "246810");
//3.获取数据库操作对象
stmt = conn.createStatement();
//4.执行sql
String sql = "select ename from emp order by ename " + keyWords;
rs = stmt.executeQuery(sql);
//5.处理查询结果集
while (rs.next()) {
System.out.println(rs.getString("ename"));
}
} catch (Exception 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();
}
}
}
}
}
1
https://gitee.com/zeng-chengjian/day24-code.git
git@gitee.com:zeng-chengjian/day24-code.git
zeng-chengjian
day24-code
day24-code
master

搜索帮助