0% found this document useful (0 votes)
14 views

New Text Document

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

New Text Document

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

package shreyasTYCM;

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.*;

public class Dbconnection extends JFrame implements ActionListener {


TextField t1, t2;
Label l1, l2;
Button submitBtn, clearBtn;
Connection con;

Dbconnection() {

l1 = new Label("Enter Roll no:");


l1.setBounds(20, 50, 100, 30);
l1.setFont(new Font("Arial", Font.BOLD, 15));

l2 = new Label("Enter Name:");


l2.setBounds(20, 100, 100, 30);
l2.setFont(new Font("Arial", Font.BOLD, 15));

t1 = new TextField();
t1.setBounds(150, 50, 200, 30);

t2 = new TextField();
t2.setBounds(150, 100, 200, 30);

submitBtn = new Button("Submit");


submitBtn.setBounds(50, 160, 100, 30);
submitBtn.addActionListener(this);

clearBtn = new Button("Clear");


clearBtn.setBounds(180, 160, 100, 30);
clearBtn.addActionListener(this);

add(l1);
add(t1);
add(l2);
add(t2);
add(submitBtn);
add(clearBtn);

setTitle("Database Connection Form");


setSize(400, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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();
}
}

public static void main(String[] args) {


new Dbconnection();
}

@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("");
}
}
}

You might also like