We will create one JFrams and name it as Collect.java. Add one new class file to our project and name it as my_update.java. In the Collect.java we will keep four JTextField and one JButton. In the second class file ( my_update.java ) we will keep the code to update the data to MySQL table.
Download Collect.java & my_update.java at the end of this tutorial
Move to Components and Add one JTextField ( variable name t1 ) ,
Similarly add 3 more JTextField ( t1, t2, t3, t4 ) , we will use them to collect Name, Class, Mark and Sex of the students and add one record using them in our student table.
Add one JButton ( variable name b1 and change the text on it to Submit )
my_update.java
Create one more class file as my_update.java . Inside this file we will add one method my_db_update(). This method will contain our MySQL connector, login access to MySQL and the query to add record.
We will copy the code given here for our my_update.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class my_update{
void my_db_update(String str1, String str2,String str3,String str4) {
try{
Class.forName("com.mysql.jdbc.Driver");
// database is my_tutorial, userid =root, password //
// Update your usrid, password and database name //
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_tutorial","root","password");
Statement st=con.createStatement();
int mark = Integer.parseInt(str3); // Mark is an integer
// Adding record
String query1="INSERT INTO `my_tutorial`.`student`"
+ " (`name`, `class`, `mark`, `sex`)"
+ "VALUES('" +str1+"','"+str2+"',"+mark+",'"+str4+"')";
st.executeUpdate(query1); // record added.
con.close();
}catch(Exception e){ System.out.println(e);}
//////////////////////////////
}
}
Creating the objects and passing data
Open our Collect.java file.
Come to design mode and double click the JButton to add ActionListener() to it.
Let us first collect the text written at JTextFieldt1 to t4 and store them in a string variable. Then create one object for class my_update and using the same to pass the string variables to my_update() method.
Execute the files. Now what ever data you enter in JTextfield of Collect.java window, will get passed to my_update.java class through method my_db_update() and record will be added.
download
Download the Java Files here ( right click and save link as to download both files ) .