Java DATABASE Connectivity
Java DATABASE Connectivity
Step 2: create a table inside the database abc. Suppose the name of table is stu. Let there are two columns in the table stu: Rno, name Step 3: write commit command. Creation of front end and Database Connectivity: import java.awt.*; import java.awt.event.*; import java.sql.* ; import java.io.*; import java.io.*; class p3 extends Frame implements ActionListener { Button b1,b2; TextField t1,t2; Label l1,l2; Connection con; p3() { try { Class.forName("com.mysql.jdbc.Driver"); } catch(Exception ex) { System.out.println("Error: unable to load driver class!"); } try { con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","user_id","pass word"); } catch(Exception ex) {
b1=new Button("insert"); b2=new Button("select"); t1=new TextField(30); t2=new TextField(30); l1=new Label("rno"); l2=new Label("name"); setLayout(new FlowLayout()); add(l1); add(t1); add(l2); add(t2); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); setSize(400,400); show(); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { try { Statement stmt=con.createStatement(); //step4 execute query int p=stmt.executeUpdate("insert into stu values("+t1.getText()+","+t2.getText());
{ try { Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from stu"); while(rs.next()) if( Integer.parseInt(t1.getText())==rs.getInt(1)) t2.setText(rs.getString(2)); } catch(Exception eee) { System.out.println(eee.getMessage()); } } } } class p4 { public static void main(String ab[]) { p3 a=new p3(); } }
Output: