📄 sqlserver.java
字号:
package sqlserver;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;import java.awt.*;import java.sql.*;import java.io.*;import java.net.*;/** * Title: Server数据库访问和操纵 * Description: Java语言演示程序:Server数据库访问和操纵,用于北京师范大学计算机系Java课程教学示范。 * Copyright: Copyright (c) 2002 * Company: 北京师范大学计算机系 * @author 孙一林 * @version 1.0 */public class sqlServer extends HttpServlet { // 定义服务器端类 public static void main(String[] args) { // Java主程序 System.out.println("等待客户端连接!"); try{ ServerSocket session= new ServerSocket(8080/*端口号*/); // 创建ServerSocket“监听”对象 handleRequests handler= null; System.out.println("等待客户端连接!"); while(true) { Socket socket= null; // 创建Socket对象 socket= session.accept(); // 接收客户端连接请求 if(socket== null) continue; System.out.println("客户连接成功"); handler= new handleRequests(socket); // 创建处理客户端请求线程对象 handler.start(); // 启动处理线程 } } catch(Exception e){ System.out.println("客户连接失败"+e); } }}class handleRequests extends Thread { // 处理客户端请求线程类 private DataInputStream in= null; // 定义接收数据流等变量 private PrintStream out= null; private Socket socket= null; Connection theConnection= null; Statement theStatement= null; ResultSet theResultSet= null; Display display= null; // 创建显示对象 public handleRequests(Socket s) throws IOException { socket= s; in= new DataInputStream(socket.getInputStream()); // 创建socket输入对象 out= new PrintStream(socket.getOutputStream()); // 创建socket输出对象 } public void openConnection(){ // 连接InterBase数据库 try{ Class.forName("interbase.interclient.Driver"); if(theConnection!= null) theConnection.close(); theConnection= DriverManager.getConnection("jdbc:interbase:student.gdb","SYSDBA","masterkey"); // 指定数据库 URL theStatement= theConnection.createStatement(); System.out.println ("加载InterBase驱动程序以及连接student.gdb数据库成功!"); display = new Display(); // 创建转换显示数据库返回的结果集对象 } catch(Exception e){ System.out.println ("连接数据库失败!"+e); } } public void run() { // 定义线程完成的功能 openConnection(); // 连接数据库 try{ String line= null; while(true) { line = in.readLine(); // 读取读客户端请求(SQL命令) if(line!= null) line= line.trim(); if(line.equals("FIND")) { // 判断是否查询(是否接收到‘FIND’字符) line = in.readLine(); line= line.trim(); theResultSet= theStatement.executeQuery(line); // 执行SQL命令,返回结果集 display.setResult(theResultSet); // 显示结果集 out.print(display.getString()); // 输出传送结果集显示数据 out.flush(); } if(line.equals("QUIT")) // 判断是否退出(是否接收到‘QUIT’字符) break; if(line.equals("HELLO")) { // 判断是否查询(是否接收到‘HELLO’字符) out.println("HELLO!欢迎查询"); out.flush(); } } in.close(); // 关闭输入、输出流 out.close(); socket.close(); // 关闭通讯 } catch(Exception e){ System.out.println(e); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -