Documente Academic
Documente Profesional
Documente Cultură
DATABASE CONNECTIVITY
JDBC API
In general, JDBC do three things:-
● Establishes a connection with a database.
● Sends SQL statements.
● Process the result.
The Driver Manager class is the management layer of
JDBC, working between the user and the drivers. It
keeps track of the drivers that are available and handles
establishing a connection between a database and the
appropriate driver.
There are mainly six steps that must be followed in order to create a database
connectivity application
DefaultTableModel
model=(DefaultTableModel)jTable1.getModel();
try
{
Class.forName("java.sql.Driver");
Connection Step-2
con=DriverManager.getConnection("jdbc:mysql://
localhost/connectivity","root",""); Step-3
Statement stmt=con.createStatement();
String query="select * from dept;"; Step-4
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
String dno=rs.getString("deptno");
String dname=rs.getString("dname");
String location=rs.getString("location");
model.addRow(new Step-5
Object[]{dno,dname,location});
}
rs.close(); Step-6
stmt.close();
con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,
e.getMessage());
}
DriverManager.getConnection("jdbc:mysql://localhost
:3306/connectivity","root","");
Statement stmt=con.createStatement();
String dno = (String)
jList2.getSelectedValue();
String SQL1 = "SELECT * FROM dept where
deptno = '"+(dno)+"';";
// Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL1);
while (rs.next()) {
jTextField1.setText(rs.getString("deptno"));
jTextField2.setText(rs.getString("dname"));
jTextField3.setText(rs.getString("location"));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(this,e.getMessage()
);
DefaultListModel
d1=(DefaultListModel)jList2.getModel();
String deptno=(String)jList2.getSelectedValue();
try
{
Class.forName("java.sql.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://loca
lhost/connectivity","root","");
Statement stmt=con.createStatement();
String q="delete from dept where
deptno="+deptno;
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
stmt.executeUpdate(q);
JOptionPane.showMessageDialog(null,"record
deleted successfully");
d1.removeAllElements();
String q1="Select deptno from dept;";
ResultSet rs=stmt.executeQuery(q1);
while(rs.next())
{
d1.addElement(rs.getString(1));
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,
e.getMessage());
}
ActionPerformed event of Delete-ALLRecoed
Button:-
DefaultListModel dmodel =
(DefaultListModel)jList1.getModel();
dmodel.removeAllElements();
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");