SQL DML (2-tier) java JDBC MySQL (2-tier) program to implement at least two MySQL queries (with and without using WHERE clause)
package a1;
import java.sql.*;
import java.lang.*;
public class JDBCDemo {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.5.7.51:3306/te25_db";
// Database credentials
static final String USER = "te25";
static final String PASS = "student";
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("connected to database successfully");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql="select * from STUDENTS";
System.out.println("Query: "+sql);
ResultSet rs=stmt.executeQuery(sql);
System.out.println("RESULT:");
System.out.println("Roll_no.\tStudentName\tMajor\t\tInstitute\t\tGPA\n");
while(rs.next()) {
int id=rs.getInt("StudentID");
String name=rs.getString("StudentName");
String major=rs.getString("Major");
int gpa=rs.getInt("GPA");
int tutid=rs.getInt("TutorID");
System.out.print(+id);
System.out.print("\t\t"+name);
System.out.print("\t\t"+major);
System.out.print("\t\t"+gpa);
System.out.print("\t\t"+tutid);
System.out.println();
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
System.out.println("\n\nGoodbye!");
}//end main
}//end FirstExample
***********OUTPUT****************************************
Connecting to database...
connected to database successfully
Creating statement...
Query: select * from STUDENTS
RESULT:
Roll_no. StudentName Major Institute GPA
101 Bill CIS 3 102
102 Mary CIS 3 0
103 Sue Marketing 4 102
104 Tom Finance 4 106
105 Alex CIS 3 106
106 Sam Marketing 4 102
107 Jane Finance 3 102
Goodbye!
Comments
Post a Comment