search
HomeJavajavaTutorialHow to display mysql in java

How to display mysql in java

May 17, 2019 pm 07:47 PM
java

Use java's swing component to draw the table, realize the functions of "add", "delete", "save" and "exit", and connect it to the mysql database.

You can extract the data from the table in the database and display it on the form containing the table, or you can write the modified content in the table into the database table.

How to display mysql in java

I used two classes to implement the above functions, one of which is MyFrame and the other is PutinStorage.

The specific code is as follows (the following codes are complete codes and have been successfully tested):

PutinStorage class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
 
import javax.swing.JOptionPane;
 
public class PutinStorage {
	// 得到数据库表数据
	public static Vector getRows(){
		String sql_url = "jdbc:mysql://localhost:3306/haha";	//数据库路径(一般都是这样写),test是数据库名称
		String name = "root";		//用户名
		String password = "123456";	//密码
		Connection conn;
		PreparedStatement preparedStatement = null;
 
		Vector rows = null;
		Vector columnHeads = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		//连接驱动
			conn = DriverManager.getConnection(sql_url, name, password);	//连接数据库
//			if(!conn.isClosed())
//				System.out.println("成功连接数据库");
			preparedStatement = conn.prepareStatement("select * from aa");
			ResultSet result1 = preparedStatement.executeQuery();
			
			if(result1.wasNull())
				JOptionPane.showMessageDialog(null, "结果集中无记录");
			
			rows = new Vector();
			
			ResultSetMetaData rsmd = result1.getMetaData();
					
			while(result1.next()){
				rows.addElement(getNextRow(result1,rsmd));
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功加载驱动。");
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功打开数据库。");
			e.printStackTrace();
		}
		return rows;
	}
	
	// 得到数据库表头
	public static Vector getHead(){
		String sql_url = "jdbc:mysql://localhost:3306/haha";	//数据库路径(一般都是这样写),test是数据库名称
		String name = "root";		//用户名
		String password = "123456";	//密码
		Connection conn;
		PreparedStatement preparedStatement = null;
 
		Vector columnHeads = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		//连接驱动
			conn = DriverManager.getConnection(sql_url, name, password);	//连接数据库
//			if(!conn.isClosed())
//				System.out.println("成功连接数据库");
			preparedStatement = conn.prepareStatement("select * from aa");
			ResultSet result1 = preparedStatement.executeQuery();
			
			boolean moreRecords = result1.next();
			if(!moreRecords)
				JOptionPane.showMessageDialog(null, "结果集中无记录");
			
			columnHeads = new Vector();
			ResultSetMetaData rsmd = result1.getMetaData();
			for(int i = 1; i <p><strong>MyFrame class : </strong></p><pre class="brush:php;toolbar:false">import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Vector;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
 
import per.tushu.storage.PutinStorage;
 
public class MyFrame extends JFrame{
	
	DefaultTableModel tableModel;		// 默认显示的表格
	JButton add,del,exit,save;		// 各处理按钮
	JTable table;		// 表格
	
	JPanel panelUP;	//增加信息的面板
	
	// 构造函数
	public MyFrame(){
		this.setBounds(300, 200, 600, 450);		// 设置窗体大小
		this.setTitle("测试");		// 设置窗体名称
		this.setLayout(new BorderLayout());	// 设置窗体的布局方式
				
		// 新建各按钮组件
		add = new JButton("增加");
		del = new JButton("删除");
		save = new JButton("保存");
		exit = new JButton("退出");
		
		panelUP = new JPanel();		// 新建按钮组件面板
		panelUP.setLayout(new FlowLayout(FlowLayout.LEFT));	// 设置面板的布局方式
		
		// 将各按钮组件依次添加到面板中
		panelUP.add(add);
		panelUP.add(del);
		panelUP.add(save);
		panelUP.add(exit);
		
		// 取得haha数据库的aa表的各行数据
		Vector rowData = PutinStorage.getRows();
		// 取得haha数据库的aa表的表头数据
		Vector columnNames = PutinStorage.getHead();
		
		
		// 新建表格
		tableModel = new DefaultTableModel(rowData,columnNames);	
		table = new JTable(tableModel);
		
		JScrollPane s = new JScrollPane(table);
		
		// 将面板和表格分别添加到窗体中
		this.add(panelUP,BorderLayout.NORTH);
		this.add(s);
		
		// 事件处理
		MyEvent();
		
		this.setVisible(true);		// 显示窗体
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		 // 设置窗体可关闭
	}
	
	// 事件处理
	public void MyEvent(){
		
		// 增加
		add.addActionListener(new ActionListener(){
 
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// 增加一行空白区域
				tableModel.addRow(new Vector());
			}
			
		});
		
		// 删除
		del.addActionListener(new ActionListener(){
 
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				// 删除指定行
				int rowcount = table.getSelectedRow();
				if(rowcount >= 0){
					tableModel.removeRow(rowcount);
				}
			}
			
		});
		
		/**
		* 保存
		* 我的解决办法是直接将aa表中的全部数据删除,
		* 将表格中的所有内容获取到,
		* 然后将表格数据重新写入aa表
		*/
		save.addActionListener(new ActionListener(){
 
			@Override
			public void actionPerformed(ActionEvent e) {	
				int column = table.getColumnCount();		// 表格列数
				int row = table.getRowCount();		// 表格行数
				
				// value数组存放表格中的所有数据
				String[][] value = new String[row][column];
				
				for(int i = 0; i <p><strong>When executing the above code, the initially displayed form is as follows: </strong></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/697/529/372/1558093588142542.png?x-oss-process=image/resize,p_40" class="lazy" title="1558093588142542.png" alt="How to display mysql in java"></p><p><strong> Click the Add button and write the content that needs to be added (I added it three times) as shown below: </strong></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/488/336/216/1558093605391393.png?x-oss-process=image/resize,p_40" class="lazy" title="1558093605391393.png" alt="How to display mysql in java"></p><p><strong>Click the Delete button to delete the specified row (I deleted Lines 2 and 4), as shown below: </strong></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/191/581/869/1558093624953964.png?x-oss-process=image/resize,p_40" class="lazy" title="1558093624953964.png" alt="How to display mysql in java"></p><p>Click the save button and you will find that the window is also closed. You can re-execute the code and you will find that the table page that appears is the same as the picture above. </p><p>Click the exit button to close the window. </p>

The above is the detailed content of How to display mysql in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

How do Java's Top Features Impact Performance and Scalability?How do Java's Top Features Impact Performance and Scalability?May 12, 2025 am 12:08 AM

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

JVM Internals: Diving Deep into the Java Virtual MachineJVM Internals: Diving Deep into the Java Virtual MachineMay 12, 2025 am 12:07 AM

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

What are the features that make Java safe and secure?What are the features that make Java safe and secure?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Must-Know Java Features: Enhance Your Coding SkillsMust-Know Java Features: Enhance Your Coding SkillsMay 11, 2025 am 12:07 AM

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

JVM the most complete guideJVM the most complete guideMay 11, 2025 am 12:06 AM

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools