1.实验目的
(1)掌握Socket通信
(2)掌握多线程的网络编程
(3)掌握使用JDBC连接数据库;
(4)对mysql数据库实现增、删、改、查操作。
2.实验要求
在Eclipse下创建Practice6项目,对未有包名要求的题目统一按照实验题名建包,然后将本题源代码放在同一包下。对有包名要求的题目按照要求建包。作业提交时将Practice6项目下src文件包命名为Practice6.src压缩后提交。
3.实验题目
Exer1:
使用InetAddress类的方法获取www.nwsuaf.edu.cn的主机的IP地址;获取本地机的名称和IP地址。程序运行结果如图所示:
package Exer1;
import java.net.*;
/*使用InetAddress类的方法获取www.nwsuaf.edu.cn的主机的IP地址;
* 获取本地机的名称和IP地址。程序运行结果如图所示:*/
public class Exer1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
InetAddress address_1 = InetAddress.getByName("www.nwsuaf.edu.cn");
System.out.println("学校IP地址:"+address_1.getHostAddress());
InetAddress address_2 = InetAddress.getLocalHost();
System.out.println("本机的IP地址:"+address_2.getHostAddress());
System.out.println("本机的名称" + address_2.getHostName());
}
catch(UnknownHostException e) {
System.out.println(e);
}
}
}
编译运行:
学校IP地址:210.27.80.3
本机的IP地址:10.118.11.165
本机的名称DESKTOP-919AKE6
Exer2:
现有一个Triangle(三角形)类:
- 服务器用于接收客户端传来的Triangle对象,计算三角形面积,将计算结果传给客户端。
- 连接服务器之前:
- 连接服务器以及提交计算请求之后:
基本要求:使用Socket类和ServerSocket类实现单线程对象的发送与接收。实现计算结果的发送与接收。可以不使用界面。
package Exer2;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(57505);
}
catch(IOException el) {
System.out.println(el);
}
try {
socketOnServer = serverForClient.accept();
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
String s = in.readUTF();
}
catch(Exception e) {
System.out.println("客户端已断开"+e);
}
}
}
package Exer2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Window win = new Window();
win.setBounds(500,500,600,500);
win.setTitle("客户端");
}
}
package Exer2;
import java.io.Serializable;
public class Triangle implements Serializable{
double sideA;
double sideB;
double sideC;
String area;
public Triangle(double a,double b,double c) {
this.sideA=a;
this.sideB=b;
this.sideC=c;
}
public boolean isLegal() {
if(sideA>0 && sideB>0 && sideC>0) {
return true;
}else {
return false;
}
}
public String calculateArea() {
double p = (sideA + sideB + sideC)/2.0;
area = "" + Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));
return area;
}
}
package Exer2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Window extends JFrame implements Runnable, ActionListener{
Triangle triangle; //使用了MVC结构
JTextField textA,textB,textC;
JTextArea showArea;
JButton controlButton,Button;
DataOutputStream out =null;
DataInputStream in = null;
Thread thread;
Window(){
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
textA = new JTextField(5);
textB = new JTextField(5);
textC = new JTextField(5);
showArea = new JTextArea();
Button = new JButton("连接到服务器");
controlButton = new JButton("Send");
JPanel pNorth = new JPanel();
pNorth.add(Button);
pNorth.add(new JLabel("sideA"));
pNorth.add(textA);
pNorth.add(new JLabel("sideB"));
pNorth.add(textB);
pNorth.add(new JLabel("sideC"));
pNorth.add(textC);
pNorth.add(controlButton);
controlButton.addActionListener(this);
Button.addActionListener(this);
add(pNorth,BorderLayout.NORTH);
add(new JScrollPane(showArea),BorderLayout.CENTER);
validate();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==controlButton) {
try {
double a = Double.parseDouble(textA.getText().trim());
double b = Double.parseDouble(textB.getText().trim());
double c = Double.parseDouble(textC.getText().trim());
triangle = new Triangle(a,b,c);
String area = triangle. calculateArea();
showArea.append("\n"+"服务器返回结果:");
showArea.append(area+"\n");
}
catch(Exception ex) {
showArea.append("\n"+ex+"\n");
}
}
else if(e.getSource()==Button) {
try {
Socket mysocket =null;
try {
mysocket = new Socket("127.0.0.1",57505);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
out.writeUTF(textA.getText());
out.writeUTF(textB.getText());
out.writeUTF(textC.getText());
}
catch(IOException e1) {
System.out.println("服务器已断开"+e1);
}
showArea.append( "连接服务器成功,当前端口地址:" + mysocket.getInetAddress() + ":"+mysocket.getPort());
}
catch(Exception ex) {
showArea.append("\n"+ex+"\n");
}
}
}
public void run() {
String s=null;
while(true) {
try {
s=in.readUTF();
showArea.append("\n"+s);
}
catch(IOException e) {
showArea.setText("与服务器已断开");
}
}
}
}
先运行Server.java,在运行Client.java。
编译运行结果:
Exer4:
员工信息管理。使用Navicat创建test数据库和tb_employee表,包含员工信息如下表所示:
员工信息表(tb_employee)
|
uname |
Sex |
salary |
1002 |
Tom |
Male |
8000 |
1003 |
Mary |
Female |
7500 |
1004 |
Peter |
Male |
5000 |
1005 |
John |
Male |
6000 |
1006 |
Sarah |
Female |
5240 |
(1)查找uid为1002的员工的username和salary,并输出到控制台;
(2)给定员工信息为:uid:1007,username: Cindy,Sex: Female, salary: 5700,将该用户信息添加到tb_employee表中;
(3)列出低于所有职工平均工资的男性(Male)员工uid和uname;
(4)删除uid为1007的员工信息。
注,连接数据的信息如下:
url = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC"
user = "root"
password = "123"
加载数据库的驱动:"com.mysql.cj.jdbc.Driver"
package Exer4;
import java.sql.*;
public class Exer4 {
public static void main(String args[]) {
Connection con = null;
Statement sql,sql1,sql2,sql3,sql4;
ResultSet rs,rs1,rs2,rs4;
int rs3;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
}
catch(Exception e) {}
String uri = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "输入自己设定的密码";
String jiLu = "(1007,'Cindy','Female',5700)";
String sqlStr = "insert into tb_employee values" + jiLu;
try {
con = DriverManager.getConnection(uri,user,password);
}
catch(SQLException e) {}
try {
sql = con.createStatement();
rs =sql.executeQuery("SELECT UNAME,SALARY FROM tb_employee WHERE UID ='1002' ");
while(rs.next()) {
String name = rs.getString(1);
int salary = rs.getInt(2);
System.out.println("查询1002的结果是:");
System.out.printf("%s\t",name);
System.out.printf("%d\t",salary);
}
System.out.printf("\n");
sql1 = con.createStatement();
int ok = sql1.executeUpdate(sqlStr);
rs1 =sql1.executeQuery("SELECT * FROM tb_employee ");
System.out.println("查询添加过1007元组的表是:");
while(rs1.next()) {
System.out.printf("%d\t%s\t%s\t%d\t",rs1.getInt(1),rs1.getString(2),rs1.getString(3),rs1.getInt(4));
System.out.printf("\n");
}
System.out.printf("\n");
sql2 = con.createStatement();
rs2 =sql2.executeQuery("SELECT UID,UNAME from tb_employee where salary "
+ "< (select avg(salary) from tb_employee where sex ='Male') ");
System.out.println("查询低于所有职工平均工资的男性(Male)员工uid和uname:");
while(rs2.next()) {
int number = rs2.getInt(1);
String name = rs2.getString(2);
System.out.printf("%s\t",number);
System.out.printf("%s\t",name);
System.out.printf("\n");
}
System.out.printf("\n");
sql3 = con.createStatement();
rs3 = sql3.executeUpdate("DELETE FROM tb_employee where uid ='1007' ");
sql4 = con.createStatement();
rs4 = sql4.executeQuery("SELECT * FROM tb_employee ");
System.out.println("查询删除过1007元组的表是:");
while(rs4.next()) {
System.out.printf("%d\t%s\t%s\t%d\t",rs4.getInt(1),rs4.getString(2),rs4.getString(3),rs4.getInt(4));
System.out.printf("\n");
}
System.out.printf("\n");
con.close();
}
catch(SQLException e) {
System.out.println(e);
}
}
}
编译运行:
查询1002的结果是:
Tom 8000
查询添加过1007元组的表是:
1002 Tom Male 8000
1003 Mary Female 7500
1004 Peter Male 5000
1005 John Male 6000
1006 Sarah Female 5240
1007 Cindy Female 5700
查询低于所有职工平均工资的男性(Male)员工uid和uname:
1004 Peter
1005 John
1006 Sarah
1007 Cindy
查询删除过1007元组的表是:
1002 Tom Male 8000
1003 Mary Female 7500
1004 Peter Male 5000
1005 John Male 6000
1006 Sarah Female 5240
Exer5:
在Mysql数据库中建立汽车产品信息表(product),内容如下:
|
Name |
Price |
Date |
A001 |
BMW 320 |
290000 |
2014-11-03 |
B002 |
Benz 200 |
340000 |
2009-12-09 |
C003 |
Audi A6 |
350000 |
2014-09-10 |
D004 |
Volkswagen Polo |
270000 |
2011-01-09 |
编写程序实现如图1查询界面。
图1
按照“ProductID”(商品编号)进行查询:输入“A001”,点击“查询”按钮,显示如图2所示:
图2
点击“清除界面字符”之后,效果显示如图1。
连接数据库操作参照任务一
package Exer5;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class WindowProduct extends JFrame implements ActionListener{
JTextField textA,textB,textC,textD;
JButton buttonseek,buttonclear;
public WindowProduct() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout());
add(new JLabel("商品编号:"));
textA = new JTextField(10);
add(textA);
buttonseek = new JButton("查询");
buttonclear = new JButton("清除界面字符");
add(buttonseek);
add(buttonclear);
add(new JLabel("商品名称:"));
textB = new JTextField(10);
add(textB);
add(new JLabel("价格:"));
textC = new JTextField(10);
add(textC);
add(new JLabel("出厂日期:"));
textD = new JTextField(10);
add(textD);
buttonseek.addActionListener(this);
buttonclear.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==buttonseek) {
String str;
str = textA.getText();
Connection con = null;
ResultSet rs;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
}
catch(Exception ex) {}
String uri = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "输入自己设定的密码";
try {
con = DriverManager.getConnection(uri,user,password);
}
catch(SQLException e1) {}
try {
String select="select* from product where productID=?";
PreparedStatement sql=con.prepareStatement(select);
sql.setString(1,str);
rs=sql.executeQuery();
while(rs.next()) {
String name = rs.getString(2);
int price = rs.getInt(3);
Date date = rs.getDate(4);
textB.setText(name);
textC.setText(String.valueOf(price));
textD.setText(String.valueOf(date));
}
con.close();
}
catch(SQLException e2) {
System.out.println(e2);
}
}
if(e.getSource() ==buttonclear) {
textA.setText("");
textB.setText("");
textC.setText("");
textD.setText("");
}
}
}
package Exer5;
import javax.swing.*;
public class Exer5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
WindowProduct win = new WindowProduct();
win.setBounds(100,50,240,280);
win.setTitle("汽车信息查询");
}
}
编译运行:
Navicat及mysql软件安装配置推荐教程:【MySQL和Navicat的安装(Windows)-哔哩哔哩】 https://b23.tv/urriu1m文章来源:https://www.toymoban.com/news/detail-774940.html
JDBC—MySQL数据库驱动:https://download.csdn.net/download/weixin_55397697/87462078?spm=1001.2014.3001.5503文章来源地址https://www.toymoban.com/news/detail-774940.html
到了这里,关于实验6 网络和JDBC数据库编程的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!