Java语言程序设计基础:数据库编程

实验目的和要求

(1) 了解JDBC的概念和工作原理。
(2) 掌握使用JDBC实现简单的数据库管理。

实验内容

(1) 建立一个student表的结构,字段包括学号、姓名、性别、年龄、班级等。
(2) 配置ODBC数据源,假设在本例中,数据源的名字是“Vtest”。
(3) 编写程序,使其可以通过图形界面向“student”表中增加数据记录。
(4) 编写程序,在“student”表中分别查询所有记录以及满足条件“年龄>18”的记录。

实验记录

(1) 建立一个student表的结构,字段包括学号、姓名、性别、年龄、班级等。

import java.sql.*;
public class jdbc1 {
	public static String driverName="com.mysql.cj.jdbc.Driver";
	public static void main(String[] args) throws SQLException {
			addStudent();
	}
	public static void addStudent() throws SQLException {
		Connection conn=null;
		ResultSet rs=null;
		try {
			Class.forName(driverName);
			System.out.println("数据驱动加载成功");
		} catch (ClassNotFoundException e) {
			System.out.println("数据驱动加载失败");
			e.printStackTrace();
		}
		try {
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/MyDB_two","root","111111");
			System.out.println("连接成功");
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("连接失败");
			e.printStackTrace();
		}
		//String sql="show create table Phone_table;";
		
		Statement sta=conn.createStatement();
		int num=0;
		//num=sta.executeUpdate("insert into Phone_Table values(2,'全球',56,'黄色);");
		num=sta.executeUpdate("create table student(sno double, sna CHAR(20), ssex CHAR(20),sage int,scla CHAR(20));");
		num+=sta.executeUpdate("insert into student values(2020021,'小红','女',19,'物联网2001');");
		num+=sta.executeUpdate("insert into student values(2020021,'小明','男',19,'通信2001');");
		rs=sta.executeQuery("select * from student;");
		System.out.println("操作了"+num+"条数据");	
		while(rs.next()) {
			double sno=rs.getInt(1);
			String name=rs.getString(2);
			String sex=rs.getString(3);
			int age=rs.getInt(4);
			String clas=rs.getString(5);
			System.out.println("学号:"+sno+"; 姓名;"+name+"; 性别:"+sex+"; 年龄:"+age+"; 班级:"+clas);
			
		}
		conn.close();
		System.out.println("查询结束");
	}
}


在这里插入图片描述
在这里插入图片描述

(2) 配置ODBC数据源,假设在本例中,数据源的名字是“Vtest”。
在这里插入图片描述

(3) 编写程序,使其可以通过图形界面向“student”表中增加数据记录。

package JDBC1;
import java.sql.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class jdbc3 {
	static Connection conn =null;
	static Statement stmt =null;
	static ResultSet rs =null;
	static PreparedStatement prestmt=null;
	//接收查询结果
	static String no;
	static String name;
	static int age_1;
	static String dept;
	static String []No=new String[100];
	static String []Name=new String[100];
	static int []Age=new int[100];
	static String []Dept=new String[100];
	static int Len=0;
	static int NPC=0;
	static int flag=0;    //判断是否连接
	private static void creatAndShowGUI() {
		JFrame f = new JFrame("SQL Server");
		f.setLayout(new FlowLayout(FlowLayout.LEFT, 200, 30));
		f.setSize(500, 300);
		f.setLocation(300, 200);
		f.setVisible(true);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JButton btn0 = new JButton("连接");
		JButton btn1 = new JButton("插入");
		JButton btn3 = new JButton("查询");
		JButton btn4 = new JButton("退出");
		f.add(btn0);
		f.add(btn1);
		f.add(btn3);
		f.add(btn4);
		// ============================连接SQL
		btn0.addActionListener(e -> {
			if (flag == 0) {
				try {
					Lianjie();
					flag = 1;// 记录已经连接
					JDialog dialog = new JDialog(f, "提示", true);
					dialog.setSize(200, 100);
					dialog.setLocation(500, 300);
					JLabel label = new JLabel("             连接数据库成功!");
					dialog.add(label);
					dialog.setVisible(true);
					dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} else {
				JDialog dialog = new JDialog(f, "提示", true);
				dialog.setSize(250, 150);
				dialog.setLocation(500, 300);
				JLabel label = new JLabel("       数据库已经连接了,不要重复操作!");
				dialog.add(label);
				dialog.setVisible(true);
				dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
			}
		});// ============================连接SQL
			// ============================断开SQL
		btn4.addActionListener(e -> {
			if (flag == 1) {
				try {
					Close();
					flag = 0;// 记录已经连接
					JDialog dialog = new JDialog(f, "提示", true);
					dialog.setSize(200, 100);
					dialog.setLocation(500, 300);
					JLabel label = new JLabel("             断开数据库成功!");
					dialog.add(label);
					dialog.setVisible(true);
					dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} else {
				JDialog dialog = new JDialog(f, "提示", true);
				dialog.setSize(250, 150);
				dialog.setLocation(500, 300);
				JLabel label = new JLabel("       数据库已经断开了,不要重复操作!");
				dialog.add(label);
				dialog.setVisible(true);
				dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
			}
		});// ============================断开SQL
		// ===============================插入
		btn1.addActionListener(e -> {
			if (flag == 1) {
				JFrame tf = new JFrame("插入");
				tf.setSize(500, 300);
				tf.setLocation(300, 200);
				tf.setVisible(true);
				tf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

				JPanel panel = new JPanel(new GridLayout(6, 2, 0, 10));

				JTextField Sno = new JTextField(20);
				JLabel label_Sno = new JLabel("Sno");

				JTextField Sname = new JTextField(20);
				JLabel label_Sname = new JLabel("Sname");

				JTextField Sage = new JTextField(20);
				JLabel label_Sage = new JLabel("Sage");

				JTextField Sdept = new JTextField(20);
				JLabel label_Sdept = new JLabel("Sdept");

				JButton btn = new JButton("确定");
				btn.addActionListener(o -> {
					String sno = Sno.getText();
					String sname = Sname.getText();
					String sage = Sage.getText();
					String sdept = Sdept.getText();
					if (sno != null && !sno.trim().equals("")) {
						int age;
						if (sage != null && !sage.trim().equals("")) {
							age = Integer.valueOf(sage);
						} else {
							age = -1;// 表示年龄未知
						}
						try {
							Insert(sno, sname, age, sdept);
							JDialog dialog = new JDialog(tf, "提示", true);
							dialog.setSize(200, 100);
							dialog.setLocation(500, 300);
							JLabel label = new JLabel("        插入成功!");
							dialog.add(label);
							dialog.setVisible(true);
							dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
						} catch (SQLException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					} else {
						JDialog dialog = new JDialog(tf, "提示", true);
						dialog.setSize(200, 100);
						dialog.setLocation(500, 300);
						JLabel label = new JLabel("      主码不能为空!");
						dialog.add(label);
						dialog.setVisible(true);
						dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
					}
				});
				panel.add(label_Sno);
				panel.add(Sno);
				panel.add(label_Sname);
				panel.add(Sname);
				panel.add(label_Sage);
				panel.add(Sage);
				panel.add(label_Sdept);
				panel.add(Sdept);
				panel.add(btn);
				tf.add(panel, BorderLayout.PAGE_END);
			} else {
				JDialog dialog = new JDialog(f, "提示", true);
				dialog.setSize(200, 100);
				dialog.setLocation(500, 300);
				JLabel label = new JLabel("             需要先连接!");
				dialog.add(label);
				dialog.setVisible(true);
				dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
			}

		});// ===============插入

		// ======================================查询
		btn3.addActionListener(e -> {
			if (flag == 1) {
				JFrame tf = new JFrame("查询");
				tf.setSize(500, 300);
				tf.setLocation(300, 200);
				tf.setVisible(true);
				tf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
				JTextArea showarea = new JTextArea(12, 34);
				JScrollPane scrollpane = new JScrollPane(showarea);
				showarea.setEditable(false);
				JPanel panel = new JPanel();

				JTextField Sno = new JTextField(20);
				JLabel label_Sno = new JLabel("Sno");

				JButton btn = new JButton("查询");
				showarea.append("学号\t姓名\t年龄\t系别\n");
				btn.addActionListener(o -> {
					String sno = Sno.getText();
					if (sno != null && !sno.trim().equals("")) {
						try {
							findUser(sno);
							if (NPC == 1) {
								String age = Integer.toString(age_1);
								showarea.append(no);
								showarea.append("\t");
								showarea.append(name);
								showarea.append("\t");
								showarea.append(age);
								showarea.append("\t");
								showarea.append(dept);
								showarea.append("\n");
								NPC = 0;
							} else {
								JDialog dialog_1 = new JDialog(tf, "提示", true);
								dialog_1.setSize(200, 100);
								dialog_1.setLocation(500, 300);
								JLabel label_1 = new JLabel("        该学生不存在!");
								dialog_1.add(label_1);
								dialog_1.setVisible(true);
								dialog_1.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
							}
						} catch (SQLException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					} else {
						JDialog dialog = new JDialog(tf, "提示", true);
						dialog.setSize(200, 100);
						dialog.setLocation(500, 300);
						JLabel label = new JLabel("      主码不能为空!");
						dialog.add(label);
						dialog.setVisible(true);
						dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
					}
				});
				panel.add(label_Sno);
				panel.add(Sno);
				panel.add(btn);
				tf.add(scrollpane, BorderLayout.PAGE_START);
				tf.add(panel, BorderLayout.PAGE_END);
			} else {
				JDialog dialog = new JDialog(f, "提示", true);
				dialog.setSize(200, 100);
				dialog.setLocation(500, 300);
				JLabel label = new JLabel("             需要先连接!");
				dialog.add(label);
				dialog.setVisible(true);
				dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
			}
		});// ======================查询

	}
	//连接SQL服务器
	public static void Lianjie() throws SQLException{
		String url ="jdbc:mysql://localhost:3306/MyDB_two";
		String username = "root";		
		String password = "111111";
		conn=DriverManager.getConnection(url,username,password);
		stmt = conn.createStatement();
	}
	//按学号查找信息
	public static boolean findUser(String Sno)  throws SQLException{
		try {
			String sql="select * from Student where Sno=?";
			prestmt = conn.prepareStatement(sql);
			prestmt.setString(1,Sno);
			rs=prestmt.executeQuery();
			if(rs.next()) {
				NPC=1;      //学号存在
				no=rs.getString("Sno");
				name=rs.getString("Sname");
				age_1=rs.getInt("Sage");
				dept=rs.getString("Sdept");
				//System.out.println(Sno1+"\t\t"+Sname+"\t\t"+Sage+"\t\t"+Sdept);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	//插入
	public static boolean Insert(String Sno,String Sname,int Sage,String Sdept)  throws SQLException{
		try {
			String sql="insert Student values(?,?,?,?)";
			prestmt = conn.prepareStatement(sql);
			prestmt.setString(1,Sno);
			prestmt.setString(2,Sname);
			prestmt.setInt(3,Sage);
			prestmt.setString(4,Sdept);
			int a= prestmt.executeUpdate();   //修改数据库,并且记录修改的条数
			if(a>0) {
				System.out.println("插入成功");
				NPC=1;
			}
			else
				System.out.println("插入修改失败");
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	//关闭数据库,关闭连接
	public static void Close() throws SQLException {
		if(rs!=null) {rs.close();}
		if(prestmt!=null) {stmt.close();}
		if(conn!=null) {conn.close();}
	}
	public static void main(String[] args) throws SQLException {
		SwingUtilities.invokeLater(jdbc3::creatAndShowGUI);
	}
}


在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(4) 编写程序,在“student”表中分别查询所有记录以及满足条件“年龄>18”的记录。

import java.sql.*;
public class jdbc1 {
	public static String driverName="com.mysql.cj.jdbc.Driver";
	public static void main(String[] args) throws SQLException {
			addStudent();
	}
	public static void addStudent() throws SQLException {
		Connection conn=null;
		ResultSet rs=null;
		try {
			Class.forName(driverName);
			System.out.println("数据驱动加载成功");
		} catch (ClassNotFoundException e) {
			System.out.println("数据驱动加载失败");
			e.printStackTrace();
		}
		try {
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/MyDB_two","root","111111");
			System.out.println("连接成功");
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("连接失败");
			e.printStackTrace();
		}
		//String sql="show create table Phone_table;";
		
		Statement sta=conn.createStatement();
		int num=0;
		rs=sta.executeQuery("select * from student where sage>18;");
		//System.out.println("操作了"+num+"条数据");	
		while(rs.next()) {
			double sno=rs.getInt(1);
			String name=rs.getString(2);
			String sex=rs.getString(3);
			int age=rs.getInt(4);
			String clas=rs.getString(5);
			System.out.println("学号:"+sno+"; 姓名;"+name+"; 性别:"+sex+"; 年龄:"+age+"; 班级:"+clas);
			
		}
		conn.close();
		System.out.println("查询结束");
	}
}

在这里插入图片描述

遇到的问题和解决方法

  • Java异常处理:SSL证书异常:SSLHandshakeException:sun.security.validator.ValidatorException-本地没有可用的证书,导致SSL校验失败,导入证书即可
  • 连接数据库报错原来是要下载相应的jar包导入
  • 表不能重复创建,重复创建会报错
  • 读取数据时,表的数据类型和存取数据类型不同也会报错,无法读取
  • 解决驱动程序无法通过使用安全套接字层(SSL)加密与 SQL Server 建立安全连接:修改jre\lib\security\java.security,删除jdk.tls.disabledAlgorithms中的3DES_EDE_CBC

心得体会

  • MySql简单的查询和插入数据
    sql = “select * from person”;
    sql = “INSERT INTO Person VALUES (‘marry’,‘女’);”;
    conn = getConnection();
    statement = conn.createStatement();
    set = statement.executeQuery(sql);

  • JDBC的全称是:Java Database Connectivity,即Java数据库连接。
    JDBC可以通过载入不同的数据库的“驱动程序”而与不同的数据库进行连接。
    那么,在数据库连接的时候,我使用的是MySQL,Java集成开发环境是Eclipse。
    要使用JDBC来访问MySQL数据库,首先需要添加MySQL数据库驱动程序。

  • Java开发任何数据库应用程序都需要4个主要接口:Driver,Connection,Statement和ResultSet。这些接口定义了使用SQL访问数据库的一般架构。访问数据库的Java程序主要有5个步骤

  • 1.加载驱动(Driver)(仅仅做一次)
    2.建立连接 (Connection)
    3.创建运行SQL的语句(Statement)
    4.运行语句
    5.获取结果(ResultSet)
    6.关闭资源

使用JDBC第一步:注冊驱动有三种方式:
Class.forName(“com.mysql.jdbc.Driver”);
推荐这样的方式,不会对详细的驱动类产生依赖

DriverManager.registerDriver(com.mysql.jdbc.Driver);
会对详细的驱动类产生依赖
System.setProperty(“jdbc.drivers”, “driver1:driver2”);

  1. ODBC(Open Database Connectivity,开放数据库互连)是微软公司开放服务结构(WOSA,Windows Open Services Architecture)中有关数据库的一个组成部分,它建立了一组规范,并提供了一组对数据库访问的标准API(应用程序编程接口)。这些API利用 SQL来完成其大部分任务。ODBC本身也提供了对SQL语言的支持,用户可以直接将SQL语句送给ODBC。

  • 一个基于ODBC的应用程序对数据库的操作不依赖任何DBMS,不直接与DBMS打交道,所有的数据库操作由对应的DBMS的ODBC驱动程序完成。也就是说,不论是FoxPro、Access还是Oracle数据库,均可用ODBC
    API进行访问。由此可见,ODBC的最大优点是能以统一的方式处理所有的数据库。

    一个完整的ODBC由下列几个部件组成:   应用程序(Application)。
      ODBC管理器(Administrator)。该程序位于Windows 控制面板(Control
    Panel)的32位ODBC内,其主要任务是管理安装的ODBC驱动程序和管理数据源。   驱动程序管理器(Driver
    Manager)。驱动程序管理器包含在ODBC32.DLL中,对用户是透明的。其任务是管理ODBC驱动程序,是ODBC中最重要的部件。
      ODBC API。   ODBC 驱动程序。是一些DLL,提供了ODBC和数据库之间的接口。
      数据源。数据源包含了数据库位置和数据库类型等信息,实际上是一种数据连接的抽象。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@小冯@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值