java整理代码,多线程与服务器,数据库编程

多线程与服务器:

Server:
public class Server {
    boolean started = false;
    ServerSocket ss = null;

    List<ChatClient> clients = new ArrayList<ChatClient>(); //保存客户端线程类 

    public static void main(String[] args) {
        new Server().start();

    }

    void start() {
        try {
            ss = new ServerSocket(8888); //建立服务端对象 
            started = true;
        } catch (BindException e) {
            System.out.println("端口使用中");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {

            while (started) {

                Socket s = ss.accept(); //接收客户端 
                ChatClient c = new ChatClient(s);
                System.out.println("客戶端接收成功");
                new Thread(c).start(); //启动线程 
                clients.add(c); //添加线程类 

            }
        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
                // TODO 自动生成 catch 块 
                e.printStackTrace();
            }
       }
    }

    class ChatClient implements Runnable { //建立客户端线程接收,发送数据 
        private Socket s;

        DataInputStream dis = null;

        DataOutputStream dos = null;

        boolean bConnected = false;

        public ChatClient(Socket s) {
            this.s = s;
            try {
                dis = new DataInputStream(s.getInputStream());
                dos = new DataOutputStream(s.getOutputStream());
                bConnected = true;
           } catch (IOException e) {

                e.printStackTrace();
            }
        }

        void send(String str) {
            try {
                dos.writeUTF(str);
            } catch (SocketException e) {
                System.out.println("對方退出了");
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        public void run() {

            try {
                while (bConnected) {

                    String str = dis.readUTF();
                    // System.out.println(str); 
                    for (int i = 0; i < clients.size(); i++) {
                        ChatClient c = clients.get(i);
                        c.send(str);
                    }

                }
            } catch (EOFException e) {
                System.out.println("客戶端退出了");
            } catch (IOException e) {
//                e.printStackTrace();
            	System.out.println("没有客户端");
            } finally {
                if (dis != null)
                    if (s != null)
                        try {
                            dis.close();
                            s.close();
                            dos.close();
                        } catch (IOException e) {

                            e.printStackTrace();
                        }

            }
        }

    }

}

Client(客户端):
public class Client extends Frame { //繼承Frame类 
    TextField tf = new TextField(); //输入框对象 

    TextArea ta = new TextArea(); //显示框对象 

    Socket s = null;

    DataOutputStream dos = null;

    DataInputStream dis = null;

    boolean bConnected = false;

    recvThread r = new recvThread(); //线程类 

    public static void main(String[] args) {

        new Client().creatFrame();
    }

    public void creatFrame() { //产生图形界面      
        this.setBounds(300, 300, 300, 300);
        ta.setEditable(false);
        this.add(tf, BorderLayout.SOUTH);
        this.add(ta, BorderLayout.NORTH);

        this.addWindowListener(new WindowAdapter() { //响应关闭窗口事件 

                    public void windowClosing(WindowEvent e) {
                        disconnect();
                        System.exit(0);
                    }

                });
        tf.addActionListener(new tfListener()); //响应输入事件 
        this.pack();
        this.setVisible(true);
        connect();
        new Thread(r).start();
    }

    public void connect() {
        try {
            s = new Socket("127.0.0.1", 8888); //建立客户端对象 
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
            bConnected = true;
        } catch (UnknownHostException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public void disconnect() { //窗口关闭时关闭客户端,输入,输出 
        try {
            dos.close();
            dis.close();
            s.close();
        } catch (IOException e) {
            
            e.printStackTrace();
        }

    }

    class tfListener implements ActionListener { //输入框实现的接口,响应输入事件 

        public void actionPerformed(ActionEvent e) {
            String str = tf.getText();
            //ta.setText(str); 
            tf.setText("");
            try {

                dos.writeUTF(str);
                dos.flush();
                //dos.close(); 
            } catch (IOException e1) {

                e1.printStackTrace();
            }

       }

    }

    class recvThread implements Runnable { //客户端线程接收数据 

        public void run() {

            try {
                while (bConnected) {
                    String str;

                    str = dis.readUTF(); //拿到数据 
                    ta.setText(ta.getText() + str + "/n");//显示到显示框中 
                }
            } catch (SocketException e) {
                System.out.println("退出了");
            } catch (IOException e1) {

                e1.printStackTrace();
            }

        }

    }

}

Java与数据库的增删改查:

Util类:public class JDBCUtil {
	private static String url;

	private static String username;

	private static String passwd;

	private static String drivername;

	static {
		Properties p = new Properties();
		try {
			p.load(new FileInputStream("db.properties"));
			// 读取文件
			url = p.getProperty("url");
			username = p.getProperty("username");
			passwd = p.getProperty("passwd");
			drivername = p.getProperty("drivername");

		} catch (IOException e) {
			// 如果文件读取出错的话,我们给这四个变量一个默认值
			e.printStackTrace();// 打印Exception的信息
			url = "jdbc:mysql://localhost:3306/student";
			username = "root";
			passwd = "";
			drivername = "com.mysql.jdbc.Driver";
		}
		// 加载数据库驱动
		try {
			Class.forName(drivername);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.exit(0);
		}

	}

	public static Connection getConnection() {
		try {
			return DriverManager.getConnection(url, username, passwd);
		} catch (SQLException e) {

			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 1、Connection 2、Statement 3、ResultSet
	 * 
	 */
	public static void close(PreparedStatement ps, Connection conn) {
		try {
			if (ps != null)
				ps.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
		try {
			close(ps, conn);
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

SQLTool类:
public class SQLTool {

	public void insertStudent(Student stu) {
		// 将这些数据写入到数据库中
		// 1、链接数据库
		Connection conn = JDBCUtil.getConnection();
		// 2、创建sql语句
		String sql = "insert into student values(?,?,?,?,?,?,?)";
		// 3、创建一个PreparedStaement
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, stu.getSno());
			ps.setString(2, stu.getSname());
			ps.setString(3, stu.getGender());
			ps.setString(4, stu.getProfessinal());
			ps.setString(5, stu.getClassis());
			ps.setString(6, stu.getGrade());
			// stu:java.util.Date
			// sql:java.sql.Date
			ps.setDate(7, new java.sql.Date(stu.getIntime().getTime()));

			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} finally {
			JDBCUtil.release(null, ps, conn);
		}

	}
	
	public void deleteStudent(String sno) {
		// 将这些数据写入到数据库中
		// 1、链接数据库
		Connection conn = JDBCUtil.getConnection();
		// 2、创建sql语句
		String sql = "delete from student where sno=?";
		// 3、创建一个PreparedStaement
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, sno);	

			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} finally {
			JDBCUtil.release(null, ps, conn);
		}

	}
	/**
	 * String sql = "update student set sname=?,gender=?,professional=?,classis=?,grade=?,intime=?" +
				" where sno=?";
	 * @param sno
	 * @return
	 */
	public void updateStudent(Student stu) {
		// 将这些数据写入到数据库中
		// 1、链接数据库
		Connection conn = JDBCUtil.getConnection();
		// 2、创建sql语句
		String sql = "update student set sname=?,gender=?,professional=?,classis=?,grade=?,intime=?" +
		" where sno=?";
		// 3、创建一个PreparedStaement
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(7, stu.getSno());
			ps.setString(1, stu.getSname());
			ps.setString(2, stu.getGender());
			ps.setString(3, stu.getProfessinal());
			ps.setString(4, stu.getClassis());
			ps.setString(5, stu.getGrade());
			// stu:java.util.Date
			// sql:java.sql.Date
			ps.setDate(6, new java.sql.Date(stu.getIntime().getTime()));


			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} finally {
			JDBCUtil.release(null, ps, conn);

		}
		JOptionPane.showConfirmDialog(null, "修改成功");

	}
	
	public Student getStudentBySno(String sno){
	
//		 将这些数据写入到数据库中
		// 1、链接数据库
		Connection conn = JDBCUtil.getConnection();
		// 2、创建sql语句
		String sql = "select * from student where sno=?";
		// 3、创建一个PreparedStaement
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, sno);
			rs = ps.executeQuery();
			if (rs.next()) {
				Student stu = new Student();
				stu.setSno(rs.getString("sno"));
				stu.setSname(rs.getString("sname"));
				stu.setGender(rs.getString("gender"));
				stu.setProfessinal(rs.getString("professional"));
				stu.setClassis(rs.getString("classis"));
				stu.setGrade(rs.getString("grade"));				
				stu.setIntime(rs.getDate("intime"));
				return stu;
			}

		} catch (SQLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} finally {
			JDBCUtil.release(rs, ps, conn);
		}
		return null;
	}
	

	public Vector getAllStudent() {
		Vector result = new Vector();
		// 讲这些数据写入到数据库中
		// 1、链接数据库
		Connection conn = JDBCUtil.getConnection();
		// 2、创建sql语句
		String sql = "select * from student";
		// 3、创建一个PreparedStaement
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);

			rs = ps.executeQuery();
			while (rs.next()) {
				Vector record = new Vector();
				record.add(rs.getString("sno"));
				record.add(rs.getString("sname"));
				record.add(rs.getString("gender"));
				record.add(rs.getString("professional"));
				record.add(rs.getString("classis"));
				record.add(rs.getString("grade"));
				Date time = rs.getDate("intime");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				record.add(sdf.format(time));
				result.add(record);
			}

		} catch (SQLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} finally {
			JDBCUtil.release(rs, ps, conn);
		}
		return result;
	}
	
	public Vector queryStudentByName(String name) {
		Vector result = new Vector();
		// 讲这些数据写入到数据库中
		// 1、链接数据库
		Connection conn = JDBCUtil.getConnection();
		// 2、创建sql语句
		String sql = "select * from student where sname like ?";
		// 3、创建一个PreparedStaement
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, "%" + name + "%");
			rs = ps.executeQuery();
			while (rs.next()) {
				Vector record = new Vector();
				record.add(rs.getString("sno"));
				record.add(rs.getString("sname"));
				record.add(rs.getString("gender"));
				record.add(rs.getString("professional"));
				record.add(rs.getString("classis"));
				record.add(rs.getString("grade"));
				Date time = rs.getDate("intime");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				record.add(sdf.format(time));
				result.add(record);
			}

		} catch (SQLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}finally {
			JDBCUtil.release(rs, ps, conn);
		}
		return result;
	}

	public Vector search(String name) {
		Vector vector = getAllStudent();
		Vector stuVector = null;
		int i = 0;
		for (; i < vector.size(); i++) {
			stuVector = (Vector) vector.get(i);
			if (stuVector.get(1).equals(name)) {
				return stuVector;

			}
		}
		if (i == vector.size()) {
			return null;
		}
		return null;
	}

}

JDBCTools {

	/**
	 * 执行 SQL 语句, 使用 PreparedStatement
	 * @param sql
	 * @param args: 填写 SQL 占位符的可变参数
	 */
	public static void update(String sql, Object ... args){
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		
		try {
			connection = JDBCTools.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			
			for(int i = 0; i < args.length; i++){
				preparedStatement.setObject(i + 1, args[i]);
			}
			
			preparedStatement.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			JDBCTools.releaseDB(null, preparedStatement, connection);
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_40629792/article/details/85163281