You are on page 1of 4

JAVA DATABASE CONNECTIVITY

import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/CODINGGROUND";

static final String USER = "root";


static final String PASS = "root";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "select * from users";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String name = rs.getString("name");
String sex = rs.getString("sex");

System.out.print("ID: " + id);

System.out.print(", Name: " + name);


System.out.print(", Age: " + age);
System.out.println(", Sex: " + sex);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
}

J TABLE
package net.codejava.swing;
import
import
import
import
import

javax.swing.JFrame;
javax.swing.JScrollPane;
javax.swing.JTable;
javax.swing.SwingUtilities;
javax.swing.table.DefaultTableModel;

public class TableExample extends JFrame


{
public TableExample()
{
//headers for the table
String[] columns = new String[] {
"Id", "Name", "Hourly Rate", "Part Time"
};
//actual data for the table in a 2d array
Object[][] data = new Object[][] {
{1, "John", 40.0, false },
{2, "Rambo", 70.0, false },
{3, "Zorro", 60.0, true },
};
final Class[] columnClass = new Class[] {
Integer.class, String.class, Double.class, Boolean.class
};
//create table model with data
DefaultTableModel model = new DefaultTableModel(data, columns) {
@Override
public boolean isCellEditable(int row, int column)
{
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
return columnClass[columnIndex];
}
};
JTable table = new JTable(model);
//add the table to the frame
this.add(new JScrollPane(table));
this.setTitle("Table Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();

this.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TableExample();
}
});
}
}

You might also like