溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java連接mysql數(shù)據(jù)庫并顯示

發(fā)布時(shí)間:2020-05-13 10:09:31 來源:億速云 閱讀:393 作者:三月 欄目:編程語言

本文主要給大家簡單講講java連接mysql數(shù)據(jù)庫并顯示,相關(guān)專業(yè)術(shù)語大家可以上網(wǎng)查查或者找一些相關(guān)書籍補(bǔ)充一下,這里就不涉獵了,我們就直奔主題吧,希望java連接mysql數(shù)據(jù)庫并顯示這篇文章可以給大家?guī)硪恍?shí)際幫助。

用java的swing組件畫出表格,實(shí)現(xiàn)“增加”、“刪除”、“保存”、“退出”的功能,并且與mysql數(shù)據(jù)庫相連接。

可以實(shí)現(xiàn)提取數(shù)據(jù)庫中表的數(shù)據(jù)顯示到含有表格的窗體上,也可以將在表格中修改的內(nèi)容寫入數(shù)據(jù)庫表中。

java連接mysql數(shù)據(jù)庫并顯示

我實(shí)現(xiàn)以上功能時(shí)用了兩個(gè)類,其中一個(gè)類是MyFrame,另外一個(gè)類是PutinStorage。

具體代碼如下(以下代碼均為完整代碼,經(jīng)測試成功的):

PutinStorage類:

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 {
	// 得到數(shù)據(jù)庫表數(shù)據(jù)
	public static Vector getRows(){
		String sql_url = "jdbc:mysql://localhost:3306/haha";	//數(shù)據(jù)庫路徑(一般都是這樣寫),test是數(shù)據(jù)庫名稱
		String name = "root";		//用戶名
		String password = "123456";	//密碼
		Connection conn;
		PreparedStatement preparedStatement = null;
 
		Vector rows = null;
		Vector columnHeads = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		//連接驅(qū)動(dòng)
			conn = DriverManager.getConnection(sql_url, name, password);	//連接數(shù)據(jù)庫
//			if(!conn.isClosed())
//				System.out.println("成功連接數(shù)據(jù)庫");
			preparedStatement = conn.prepareStatement("select * from aa");
			ResultSet result1 = preparedStatement.executeQuery();
			
			if(result1.wasNull())
				JOptionPane.showMessageDialog(null, "結(jié)果集中無記錄");
			
			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("未成功加載驅(qū)動(dòng)。");
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功打開數(shù)據(jù)庫。");
			e.printStackTrace();
		}
		return rows;
	}
	
	// 得到數(shù)據(jù)庫表頭
	public static Vector getHead(){
		String sql_url = "jdbc:mysql://localhost:3306/haha";	//數(shù)據(jù)庫路徑(一般都是這樣寫),test是數(shù)據(jù)庫名稱
		String name = "root";		//用戶名
		String password = "123456";	//密碼
		Connection conn;
		PreparedStatement preparedStatement = null;
 
		Vector columnHeads = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		//連接驅(qū)動(dòng)
			conn = DriverManager.getConnection(sql_url, name, password);	//連接數(shù)據(jù)庫
//			if(!conn.isClosed())
//				System.out.println("成功連接數(shù)據(jù)庫");
			preparedStatement = conn.prepareStatement("select * from aa");
			ResultSet result1 = preparedStatement.executeQuery();
			
			boolean moreRecords = result1.next();
			if(!moreRecords)
				JOptionPane.showMessageDialog(null, "結(jié)果集中無記錄");
			
			columnHeads = new Vector();
			ResultSetMetaData rsmd = result1.getMetaData();
			for(int i = 1; i <= rsmd.getColumnCount(); i++)
				columnHeads.addElement(rsmd.getColumnName(i));
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功加載驅(qū)動(dòng)。");
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功打開數(shù)據(jù)庫。");
			e.printStackTrace();
		}
		return columnHeads;
	}
	
	// 得到數(shù)據(jù)庫中下一行數(shù)據(jù)
	private static Vector getNextRow(ResultSet rs,ResultSetMetaData rsmd) throws SQLException{
		Vector currentRow = new Vector();
		for(int i = 1; i <= rsmd.getColumnCount(); i++){
			currentRow.addElement(rs.getString(i));
		}
		return currentRow;
	}
	
	/*//主函數(shù)
	public static void main(String[] args){
		getRows();
	}*/
}

MyFrame類:

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;		// 默認(rèn)顯示的表格
	JButton add,del,exit,save;		// 各處理按鈕
	JTable table;		// 表格
	
	JPanel panelUP;	//增加信息的面板
	
	// 構(gòu)造函數(shù)
	public MyFrame(){
		this.setBounds(300, 200, 600, 450);		// 設(shè)置窗體大小
		this.setTitle("測試");		// 設(shè)置窗體名稱
		this.setLayout(new BorderLayout());	// 設(shè)置窗體的布局方式
				
		// 新建各按鈕組件
		add = new JButton("增加");
		del = new JButton("刪除");
		save = new JButton("保存");
		exit = new JButton("退出");
		
		panelUP = new JPanel();		// 新建按鈕組件面板
		panelUP.setLayout(new FlowLayout(FlowLayout.LEFT));	// 設(shè)置面板的布局方式
		
		// 將各按鈕組件依次添加到面板中
		panelUP.add(add);
		panelUP.add(del);
		panelUP.add(save);
		panelUP.add(exit);
		
		// 取得haha數(shù)據(jù)庫的aa表的各行數(shù)據(jù)
		Vector rowData = PutinStorage.getRows();
		// 取得haha數(shù)據(jù)庫的aa表的表頭數(shù)據(jù)
		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);		 // 設(shè)置窗體可關(guān)閉
	}
	
	// 事件處理
	public void MyEvent(){
		
		// 增加
		add.addActionListener(new ActionListener(){
 
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// 增加一行空白區(qū)域
				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表中的全部數(shù)據(jù)刪除,
		* 將表格中的所有內(nèi)容獲取到,
		* 然后將表格數(shù)據(jù)重新寫入aa表
		*/
		save.addActionListener(new ActionListener(){
 
			@Override
			public void actionPerformed(ActionEvent e) {	
				int column = table.getColumnCount();		// 表格列數(shù)
				int row = table.getRowCount();		// 表格行數(shù)
				
				// value數(shù)組存放表格中的所有數(shù)據(jù)
				String[][] value = new String[row][column];
				
				for(int i = 0; i < row; i++){
					for(int j = 0; j < column; j++){
						value[i][j] = table.getValueAt(i, j).toString();
					}
				}
				
				// 以下均為對(duì)數(shù)據(jù)庫的操作
				String sql_url = "jdbc:mysql://localhost:3306/haha";	//數(shù)據(jù)庫路徑(一般都是這樣寫),haha是數(shù)據(jù)庫名稱
				String name = "root";		//用戶名
				String password = "123456";	//密碼
				Connection conn;
				PreparedStatement preparedStatement = null;
 
				try {
					Class.forName("com.mysql.jdbc.Driver");		//連接驅(qū)動(dòng)
					conn = DriverManager.getConnection(sql_url, name, password);	//連接數(shù)據(jù)庫
					if(!conn.isClosed())
						System.out.println("成功連接數(shù)據(jù)庫");
					
					// 刪除aa表中所有數(shù)據(jù)
					preparedStatement = conn.prepareStatement("delete from aa where true");
					preparedStatement.executeUpdate();
					
					// 將value數(shù)組中的數(shù)據(jù)依次存放到aa表中
					for(int i = 0; i < row; i++){
						preparedStatement = conn.prepareStatement("insert into aa values(" + Integer.parseInt(value[i][0]) + ",'" + value[i][1] + "')");
						preparedStatement.executeUpdate();
					}
					
				} catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					System.out.println("未成功加載驅(qū)動(dòng)。");
					e1.printStackTrace();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					System.out.println("未成功打開數(shù)據(jù)庫。");
					e1.printStackTrace();
				}
				
				// 保存后退出
				System.exit(0);
			}
		});
		
		// 退出
		exit.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
				System.exit(0);
			}
				
		});
	}
	
	// 主函數(shù)
	public static void main(String[] args){
		new MyFrame();
	}
}

執(zhí)行以上代碼的時(shí)候,最初顯示的窗體如下所示:

java連接mysql數(shù)據(jù)庫并顯示

點(diǎn)擊增加按鈕并寫入需要增加的內(nèi)容(我增加了三次)如下圖:

java連接mysql數(shù)據(jù)庫并顯示

點(diǎn)擊刪除按鈕,刪除指定行(我刪除了第2行和第4行),如下圖:

java連接mysql數(shù)據(jù)庫并顯示

點(diǎn)擊保存按鈕,會(huì)發(fā)現(xiàn)窗口也關(guān)閉了。這是你可以再重新執(zhí)行代碼,會(huì)發(fā)現(xiàn)出現(xiàn)的表格頁面與上圖一樣。

點(diǎn)擊退出按鈕,關(guān)閉窗口。

java連接mysql數(shù)據(jù)庫并顯示就先給大家講到這里,對(duì)于其它相關(guān)問題大家想要了解的可以持續(xù)關(guān)注我們的行業(yè)資訊。我們的板塊內(nèi)容每天都會(huì)捕捉一些行業(yè)新聞及專業(yè)知識(shí)分享給大家的。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI