New Text Document
New Text Document
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Dbconnection() {
t1 = new TextField();
t1.setBounds(150, 50, 200, 30);
t2 = new TextField();
t2.setBounds(150, 100, 200, 30);
add(l1);
add(t1);
add(l2);
add(t2);
add(submitBtn);
add(clearBtn);
try {
Class.forName("com.mysql.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
System.out.println("Connection Established Successfully!!!");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitBtn)
{
String name="";
String rollno="";
rollno = t1.getText();
name = t2.getText();
if(rollno != "" && name != "")
{
try
{
PreparedStatement pstmt = con.prepareStatement("INSERT INTO
stud VALUES (?, ?)");
pstmt.setString(1, rollno);
pstmt.setString(2, name);
int i = pstmt.executeUpdate();
if (i > 0)
{
System.out.println("Data Inserted Successfully");
}
PreparedStatement pstmt1 = con.prepareStatement("Select * from
stud where r_no=?");
pstmt1.setString(1, rollno);
ResultSet rs = pstmt1.executeQuery();
while (rs.next())
{
JOptionPane.showMessageDialog(this,
"Data Inserted Succesfully \nInserted Data: " +
rs.getString(1) + " " + rs.getString(2),
"SuccessFully",
JOptionPane.INFORMATION_MESSAGE);
}
t1.setText("");
t2.setText("");
} catch (SQLException ex)
{
ex.printStackTrace();
}
} else{
JOptionPane.showMessageDialog(this, "Please fill in all fields",
"Error", JOptionPane.ERROR_MESSAGE);
}
} else if (e.getSource() == clearBtn) {
t1.setText("");
t2.setText("");
}
}
}