Insert/Add Data from Java(JFrame Frontend) into My Sql(Backend-Database)
First to make sure that Database Connection is in place and proper My sql Driver is in place by
adding JAR file in Build path option in Java eclipse. Following is the code for successful database
connection.
public static Connection getConnection() throws Exception{
try {
String driver="com.mysql.cj.jdbc.Driver";
String url="jdbc:mysql://127.0.0.1:3306/sch_db";
String username="root";
String password="Pintoo@1404";
Class.forName(driver);
Connection conn=(Connection) DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e) {System.out.println(e);}
return null;
}
Insert/add data entered by user:
public static void postrec() throws Exception{
try {
Connection conn=getConnection();
PreparedStatement posted= conn.prepareStatement("INSERT INTO sch_db.STUDENT(ST_ID,ST_name,ST_Gender,ST_DOB,ST_CLASS,ST_SECTION,st_house) VALUES(?,?,?,?,?,?,?)");
posted.setString(1,student_id.getText());
posted.setString(2,stud_name.getText());
posted.setString(3,dispgender.getText());
posted.setString(4,st_dob.getText());
posted.setString(5,dispclass.getText());
posted.setString(6,dispsection.getText());
posted.setString(7,st_house.getText());
posted.executeUpdate();
JOptionPane.showMessageDialog(null,"1 Record applied and saved");
}
catch(Exception ez){System.out.println(ez);}
finally {
//JOptionPane.showMessageDialog(null," ");
System.out.println(" ");
}
}
Comments
Post a Comment