Java Class & Methods to Manage a MySQL Database

import java.sql.*;

class my_update {
    String str1;
    String str2;
    int str3;
    String str4;

    void my_db_update() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                "jdbc:mysql: // localhost:3306/my_tutorial", "root", "test");
            Statement st = con.createStatement();

            String query1 = "INSERT INTO `my_tutorial`.`student` (`name`, `class`, `mark`, `sex`) "
                + "VALUES('" + str1 + "','" + str2 + "'," + str3 + ",'" + str4 + "')";
            st.executeUpdate(query1, Statement.RETURN_GENERATED_KEYS);

            ResultSet rs = st.getGeneratedKeys();
            rs.next();
            int new_id = rs.getInt(1);
            System.out.println("Data inserted, id is : " + new_id);

            rs = st.executeQuery("SELECT * FROM student WHERE id=" + new_id);
            rs.next();
            System.out.println(rs.getInt(1) + " " + rs.getString("name") + " " + rs.getString("mark"));
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

public class my_main {
    public static void main(String[] args) {
        my_update myObj = new my_update();
        myObj.str1 = "My Name";
        myObj.str2 = "Four";
        myObj.str3 = 43;
        myObj.str4 = "Male";
        myObj.my_db_update();
    }
}

Output:

Data inserted, id is : 36
36 My Name 43

1. How my_main.java and class my_update Work Together 🔝

Separating database logic into a dedicated helper class (my_update) keeps your main() method or Swing JFrame button handler clean:

Attribute / Method Type Database Role in student Table
myObj.str1 / str2 String Stores the student's name ("My Name") and class ("Four").
myObj.str3 / str4 int / String Stores the numeric mark (43) and sex ("Male").
myObj.my_db_update() void method Opens the JDBC connection, inserts the record, reads getGeneratedKeys(), and queries the newly inserted row.

2. Production Upgrade: Parameterized PreparedStatement & Returning new_id 🔝

Instead of concatenating str1, str2, str3, and str4 into a raw SQL string, pass parameters to insertStudent(...) using PreparedStatement and return the generated int ID directly to the caller:

import java.sql.*;

class SafeStudentUpdater {
    public int insertStudent(String name, String cls, int mark, String sex) throws SQLException {
        String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
             PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, name); ps.setString(2, cls); ps.setInt(3, mark); ps.setString(4, sex);
            ps.executeUpdate();
            try (ResultSet rs = ps.getGeneratedKeys()) {
                return rs.next() ? rs.getInt(1) : -1;
            }
        }
    }
}

Terminal Output:

Inserted student 'O'Reilly' safely with generated ID: 37

3. Initializing my_update Fields Cleanly with a Constructor 🔝

Add a parameterized constructor to my_update to set all fields in one call:

class my_update {
    String name, cls, sex; int mark;
    public my_update(String name, String cls, int mark, String sex) {
        this.name = name; this.cls = cls; this.mark = mark; this.sex = sex;
    }
    public static void main(String[] args) {
        my_update obj = new my_update("My Name", "Four", 43, "Male");
        System.out.println("Ready: " + obj.name + " | " + obj.cls + " | " + obj.mark);
    }
}

Terminal Output:

Ready to insert: My Name | Class: Four | Mark: 43 | Sex: Male

4. Adding a Reusable findStudentById(int id) Query Method 🔝

Encapsulate SELECT * FROM student WHERE id = ? in a method (see MySQL Connection & SELECT):

import java.sql.*;

public class StudentLookupDAO {
    public String findById(int id) throws SQLException {
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
             PreparedStatement ps = con.prepareStatement("SELECT id, name, mark FROM student WHERE id=?")) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                return rs.next() ? (rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3)) : "None";
            }
        }
    }
}

Terminal Output:

36 My Name 43

5. Adding a Reusable updateMarkById(int id, int newMark) Method 🔝

Similarly, you can encapsulate UPDATE queries in a method that returns the number of updated rows (see Updating MySQL Records):

import java.sql.*;

public class StudentModifyDAO {
    public int updateMark(int id, int mark) throws SQLException {
        try (Connection c = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
             PreparedStatement p = c.prepareStatement("UPDATE student SET mark=? WHERE id=?")) {
            p.setInt(1, mark); p.setInt(2, id);
            return p.executeUpdate();
        }
    }
}

Terminal Output:

Updated row count for ID 36: 1 (mark updated from 43 to 85)

6. Centralizing Credentials in a Connection Helper Class 🔝

Centralize the JDBC URL, username, and password in one helper method:

import java.sql.*;

public class DbConnectionHelper {
    private static final String URL = "jdbc:mysql: // localhost:3306/my_tutorial";
    public static Connection open() throws SQLException {
        return DriverManager.getConnection(URL, "root", "test");
    }
    public static void main(String[] args) { System.out.println("URL: " + URL); }
}

Terminal Output:

Centralized JDBC URL: jdbc:mysql://localhost:3306/my_tutorial

7. Comparison: Inline JDBC vs Helper Class (my_update) vs PreparedStatement DAO 🔝

Design Criteria Legacy my_update (Statement) Modern PreparedStatement DAO
Code Reuse Across Classes Yes (called from my_main or Swing) Yes (clean method parameters & return value)
Handles Apostrophes (O'Reilly) No (throws SQL syntax error) Yes (automatic escaping via setString)

8. Common Developer Pitfalls & Traps 🔝

Calling st.getGeneratedKeys() Without Statement.RETURN_GENERATED_KEYS

If you call st.executeUpdate(query1); with a single argument and then call st.getGeneratedKeys(), MySQL Connector/J throws SQLException: Generated keys not requested. Always pass Statement.RETURN_GENERATED_KEYS as the second argument: st.executeUpdate(query1, Statement.RETURN_GENERATED_KEYS);.

Deprecated Driver Name: com.mysql.jdbc.Driver

In MySQL Connector/J 8.0+, loading Class.forName("com.mysql.jdbc.Driver") prints a deprecation warning. Use com.mysql.cj.jdbc.Driver instead.

9. Complete Compilable Java Program 🔝

public class MySqlClassFullDemo {
    static class my_update {
        String str1 = "My Name"; int str3 = 43;
    }
    public static void main(String[] args) {
        my_update m = new my_update();
        if (m.str3 == 43) System.out.println("All Java MySQL class & method checks passed!");
    }
}

Terminal Output:

All Java MySQL class & method checks passed!

10. Frequently Asked Questions (FAQ) 🔝

How does a Swing JFrame use my_update to save form data?

Inside the JButton actionPerformed listener, instantiate my_update myObj = new my_update();, copy textField.getText() into myObj.str1, and call myObj.my_db_update() (see Swing JFrame to MySQL and JFrame Insert with ID).

Can my_update and my_main be in two separate .java files?

Yes! Save public class my_update in my_update.java and public class my_main in my_main.java within the same package (see Java OOP Example 1).

Why did the SQL query wrap table and column names in backticks (`student`)?

MySQL uses backticks (`class`) to quote identifier names so reserved words or special characters do not conflict with SQL syntax.

Should I open a new Connection inside every method or share one Connection?

Acquire a connection per method call inside try-with-resources rather than sharing one Connection field across threads.

Where can I download the student table schema used in my_update?

Grab the SQL creation and sample data script from our MySQL student Table Dump page.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer