Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone



Clound SSD Virtual Server

Java GUI and MySQL Database

Java GUI and MySQL Database (Java) หัวข้อนี้จะเป็นการเขียน Java GUI กับการติดต่อกับฐานข้อมูล Database ของ MySQL แบบง่าย ๆ โดยจะยกตัวอย่างการเขียนเพื่อติดต่อกับ MySQL เช่น การเชื่อมต่อว่ามีวิธีการอย่างไร การอ่านข้อมูลจาก MySQL มาแสดงในหน้า JFrame บน JTable ในรูปแบบของ Column/Rows และตัวอย่าง Code สำหรับการ Insert ข้อมูล , Update ข้อมูล และการ Delete ข้อมูล ซึ่งตัวอย่างนี้สามารถนำไปประยุกต์ใช้งานกับการเขียน Java GUI กับ Databae MySQL ได้หลากหลาย

Java GUI and MySQL Database

Java GUI and MySQL Database


Basic Java and MySQL Database (JDBC/com.mysql.jdbc.Driver)


โครงสร้าง Database และ JAR Library

Java GUI and MySQL Database

ไฟล์ Library ของ jar ไว้ติดต่อกับ Database ของ MySQL

Table
CREATE TABLE `customer` (
  `CustomerID` varchar(4) NOT NULL,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `CountryCode` varchar(2) NOT NULL,
  `Budget` double NOT NULL,
  `Used` double NOT NULL,
  PRIMARY KEY  (`CustomerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- 
-- dump ตาราง `customer`
-- 

INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John  Smith', '[email protected]', 'UK', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);


Java GUI and MySQL Database

โครงสร้างของ Database

รูปแบบการเชื่อมต่อระหว่าง Java GUI กับ MySQL

Connection connect = null;

try {
	Class.forName("com.mysql.jdbc.Driver");

	connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
			"?user=root&password=root");

	if(connect != null){
		System.out.println("Database Connected.");
	} else {
		System.out.println("Database Connect Failed.");
	}
	
} catch (Exception e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}

try {
	connect.close();
} catch (SQLException e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}


Example ตัวอย่างการเขียน Java GUI เพื่ออ่านข้อมูลจาก MySQL มาแสดงในหน้า JFrame บน JTable

อ่านบทความ Java GUI กับ JTable วิธีการใช้งาน JTable พื้นฐาน (แนะนำ)


MyForm.java
package com.java.myapp;

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;

public class MyForm extends JFrame {
	
	Connection connect = null;
	Statement s = null;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				MyForm frame = new MyForm();
				frame.setVisible(true);
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MyForm() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 579, 242);
		setTitle("ThaiCreate.Com Java GUI Tutorial");
		getContentPane().setLayout(null);
		
		// Customer Label
		JLabel lblCustomer = new JLabel("Customer List");
		lblCustomer.setBounds(231, 28, 95, 14);
		getContentPane().add(lblCustomer);
		
		// ScrollPane for Table
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(33, 61, 494, 90);
		getContentPane().add(scrollPane);
		
		// Table
		JTable table = new JTable();
				
		// Model for Table
		DefaultTableModel model = (DefaultTableModel)table.getModel();
		model.addColumn("CustomerID");
		model.addColumn("Name");
		model.addColumn("Email");
		model.addColumn("CountryCode");
		model.addColumn("Budget");
		model.addColumn("Used");
		
		try {
			Class.forName("com.mysql.jdbc.Driver");

			connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
					"?user=root&password=root");
			
			s = connect.createStatement();
			
			String sql = "SELECT * FROM  customer ORDER BY CustomerID ASC";
			
			ResultSet rec = s.executeQuery(sql);
			int row = 0;
			while((rec!=null) && (rec.next()))
            {			
				model.addRow(new Object[0]);
				model.setValueAt(rec.getString("CustomerID"), row, 0);
				model.setValueAt(rec.getString("Name"), row, 1);
				model.setValueAt(rec.getString("Email"), row, 2);
				model.setValueAt(rec.getString("CountryCode"), row, 3);
				model.setValueAt(rec.getFloat("Budget"), row, 4);
				model.setValueAt(rec.getFloat("Used"), row, 5);
				row++;
				
				/*
				 * 		model.addRow(new Object[]{
						rec.getString("CustomerID")
						,rec.getString("Name"),rec.getString("Email")
						,rec.getString("CountryCode")
						,rec.getString("Budget")
						,rec.getString("Used")
						});
				 */
            }
			rec.close();
             
		} catch (Exception e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, e.getMessage());
			e.printStackTrace();
		}
		
		try {
			if(s != null) {
				s.close();
				connect.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		scrollPane.setViewportView(table);		

	}
}

Output

Java GUI and MySQL Database

ผลลัพธ์ที่ได้จากการอ่านข้อมูงจาก Database มาแสดงใน JTable และสำหรับการใช้งานพื้นฐาน JTable แนะนำให้อ่านบทความของ JTable








ตัวอย่างรูปแบบการเชื่อมต่อและกระทำกับ Database เช่น Add Insert/Update/Delete

Insert
Connection connect = null;
Statement s = null;

try {
	Class.forName("com.mysql.jdbc.Driver");

	connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
			"?user=root&password=root");
	
	s = connect.createStatement();
	
	String sql = "INSERT INTO customer " +
			"(CustomerID,Name,Email,CountryCode,Budget,Used) " + 
			"VALUES ('C005','Chai Surachai','[email protected]'" +
			",'TH','1000000','0') ";
	 s.execute(sql);
	
	 System.out.println("Record Inserted Successfully");
	 
} catch (Exception e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}

try {
	if(s != null) {
		s.close();
		connect.close();
	}
} catch (SQLException e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}


Read
Connection connect = null;
Statement s = null;

try {
	Class.forName("com.mysql.jdbc.Driver");

	connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
			"?user=root&password=root");
	
	s = connect.createStatement();
	
	String sql = "SELECT * FROM  customer ORDER BY CustomerID ASC";
	
	ResultSet rec = s.executeQuery(sql);
	
	while((rec!=null) && (rec.next()))
	{
		System.out.print(rec.getString("CustomerID"));
		System.out.print(" - ");
		System.out.print(rec.getString("Name"));
		System.out.print(" - ");
		System.out.print(rec.getString("Email"));
		System.out.print(" - ");
		System.out.print(rec.getString("CountryCode"));
		System.out.print(" - ");
		System.out.print(rec.getFloat("Budget"));
		System.out.print(" - ");
		System.out.print(rec.getFloat("Used"));
		System.out.println("");
	}
	rec.close();

} catch (Exception e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}

try {
	if(s != null) {
		s.close();
		connect.close();
	}
} catch (SQLException e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}


Update
Connection connect = null;
Statement s = null;

try {
	Class.forName("com.mysql.jdbc.Driver");

	connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
			"?user=root&password=root");
	
	s = connect.createStatement();
	
	String sql = "UPDATE customer " +
			"SET Budget = '5000000' " +
			" WHERE CustomerID = 'C005' ";
	 s.execute(sql);
	
	 System.out.println("Record Update Successfully");
	 
} catch (Exception e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}

try {
	if(s != null) {
		s.close();
		connect.close();
	}
} catch (SQLException e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}


Delete
Connection connect = null;
Statement s = null;

try {
	Class.forName("com.mysql.jdbc.Driver");

	connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
			"?user=root&password=root");
	
	s = connect.createStatement();
	
	String sql = "DELETE FROM customer " +
			" WHERE CustomerID = 'C005' ";
	 s.execute(sql);
	
	 System.out.println("Record Delete Successfully");

} catch (Exception e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}

try {
	if(s != null) {
		s.close();
		connect.close();
	}
} catch (SQLException e) {
	// TODO Auto-generated catch block
	System.out.println(e.getMessage());
	e.printStackTrace();
}


สำหรับการใช้งาน Java GUI กับ MySQL สามารถอ่านเพิ่มเติมได้ที่บทความ Java กับ MySQL

Java GUI and MySQL Database

Java and MySQL Database (JDBC/com.mysql.jdbc.Driver)









   
Share

Property & Method (Others Related)

Java GUI and Database Connection
Java GUI and MS Access Database
Java GUI and MariaDB Database
Java GUI and SQL Server Database
Java GUI and Oracle Database
Java GUI and Azure SQL Database (Windows Azure)

ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2013-09-06 13:22:58 / 2017-03-27 21:33:46
  Download : No files
 Sponsored Links / Related

 
Java GUI and Database Connection
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่