Connect to a Database
import java.sql.*;
public class jdbcConn
{
public static void main(String[] args)
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("Class not found "+ e);
}
System.out.println("Jdbc Class found");
int no_of_rows = 0;
try
{
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * from employee");
while (rs.next())
{
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
}
catch(SQLException e)
{
System.out.println("SQL exception occured" + e);
}
}
}
Edit Table
import java.sql.*;
public class jdbcConn
{
public static void main(String[] args) throws Exception
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username","password");
Statement stmt = con.createStatement();
String query ="create table employees (id integer primary key, first_name char(50),last_name char(75))";
stmt.execute(query);
System.out.println("Employee table created");
String query1 = "alter table employees add
address Char(100) ";
String query2 = "alter table employees drop
column last_name";
stmt.execute(query1);
stmt.execute(query2);
System.out.println("Address column added to the table
& last_name column removed from the table");
String query3 = "drop table employees";
stmt.execute(query3);
System.out.println("Employees table removed");
}
}
No comments:
Post a Comment