0% found this document useful (0 votes)
14 views6 pages

Import Javax

The document contains a Java program for a Student Manager application that uses a SQLite database to manage student records. It features a graphical user interface (GUI) for adding and viewing students, and includes basic error handling for user input. Additionally, it demonstrates simple server-client communication using sockets for network programming.

Uploaded by

6wqtrst5h2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views6 pages

Import Javax

The document contains a Java program for a Student Manager application that uses a SQLite database to manage student records. It features a graphical user interface (GUI) for adding and viewing students, and includes basic error handling for user input. Additionally, it demonstrates simple server-client communication using sockets for network programming.

Uploaded by

6wqtrst5h2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

import javax.swing.

*;

import java.awt.*;

import java.awt.event.*;

import java.sql.*;

import java.net.*;

import java.io.*;

public class StudentManager {

// Database credentials

static final String DB_URL = "jdbc:sqlite:students.db";

public static void main(String[] args) {

// Setup database

setupDatabase();

// Create GUI

SwingUtilities.invokeLater(StudentManager::createGUI);

private static void setupDatabase() {

try (Connection conn = DriverManager.getConnection(DB_URL);

Statement stmt = conn.createStatement()) {

String sql = "CREATE TABLE IF NOT EXISTS students (

id INTEGER PRIMARY KEY AUTOINCREMENT,

name TEXT NOT NULL,

age INTEGER NOT NULL

);";
stmt.execute(sql);

} catch (SQLException e) {

System.err.println("Error setting up database: " + e.getMessage());

private static void createGUI() {

JFrame frame = new JFrame("Student Manager");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 300);

JPanel panel = new JPanel(new GridLayout(4, 2));

JLabel nameLabel = new JLabel("Name:");

JTextField nameField = new JTextField();

JLabel ageLabel = new JLabel("Age:");

JTextField ageField = new JTextField();

JButton addButton = new JButton("Add Student");

JButton viewButton = new JButton("View Students");

panel.add(nameLabel);

panel.add(nameField);

panel.add(ageLabel);

panel.add(ageField);

panel.add(addButton);

panel.add(viewButton);

frame.add(panel);

frame.setVisible(true);
// Add button action listener

addButton.addActionListener(e -> {

String name = nameField.getText();

String ageText = ageField.getText();

if (name.isEmpty() || ageText.isEmpty()) {

JOptionPane.showMessageDialog(frame, "Please enter both name and age.", "Error",


JOptionPane.ERROR_MESSAGE);

return;

try {

int age = Integer.parseInt(ageText);

addStudentToDatabase(name, age);

JOptionPane.showMessageDialog(frame, "Student added successfully!", "Success",


JOptionPane.INFORMATION_MESSAGE);

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(frame, "Invalid age entered.", "Error",


JOptionPane.ERROR_MESSAGE);

});

// View button action listener

viewButton.addActionListener(e -> fetchStudentsFromDatabase(frame));

private static void addStudentToDatabase(String name, int age) {

String sql = "INSERT INTO students (name, age) VALUES (?, ?)";

try (Connection conn = DriverManager.getConnection(DB_URL);

PreparedStatement pstmt = conn.prepareStatement(sql)) {

pstmt.setString(1, name);

pstmt.setInt(2, age);
pstmt.executeUpdate();

} catch (SQLException e) {

System.err.println("Error adding student: " + e.getMessage());

private static void fetchStudentsFromDatabase(JFrame frame) {

String sql = "SELECT * FROM students";

try (Connection conn = DriverManager.getConnection(DB_URL);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql)) {

StringBuilder result = new StringBuilder("Student List:\n");

while (rs.next()) {

result.append("ID: ").append(rs.getInt("id"))

.append(", Name: ").append(rs.getString("name"))

.append(", Age: ").append(rs.getInt("age"))

.append("\n");

JOptionPane.showMessageDialog(frame, result.toString(), "Student List",


JOptionPane.INFORMATION_MESSAGE);

} catch (SQLException e) {

System.err.println("Error fetching students: " + e.getMessage());

// Example of a simple server-client communication (Network Programming)

static class SimpleServer {


public static void startServer() {

new Thread(() -> {

try (ServerSocket serverSocket = new ServerSocket(12345)) {

System.out.println("Server started on port 12345...");

while (true) {

Socket client = serverSocket.accept();

try (BufferedReader in = new BufferedReader(new


InputStreamReader(client.getInputStream()));

PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {

String received = in.readLine();

out.println("Hello, " + received + "! From Server.");

} catch (IOException e) {

System.err.println("Server error: " + e.getMessage());

}).start();

static class SimpleClient {

public static void sendMessage(String message) {

new Thread(() -> {

try (Socket socket = new Socket("localhost", 12345);

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

out.println(message);

System.out.println("Server response: " + in.readLine());


} catch (IOException e) {

System.err.println("Client error: " + e.getMessage());

}).start();

You might also like