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
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. |
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
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
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
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)
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
| 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) |
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);.
In MySQL Connector/J 8.0+, loading Class.forName("com.mysql.jdbc.Driver") prints a deprecation warning. Use com.mysql.cj.jdbc.Driver instead.
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!
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).
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).
MySQL uses backticks (`class`) to quote identifier names so reserved words or special characters do not conflict with SQL syntax.
Acquire a connection per method call inside try-with-resources rather than sharing one Connection field across threads.
Grab the SQL creation and sample data script from our MySQL student Table Dump page.
INSERT tutorial.my_update.new_id to a Swing form.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.