Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package template1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
*
* @author Manas9
*/
public class Template1 {
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
// TODO code application logic here
System.out.println("main block executing ");
Connection c = null; Statement st = null;
ResultSet rs = null; // result set object
String dbURL = "jdbc:mysql://localhost/test?";
String user = "Manas9"; String pwd = "Manas9237";
Properties param = new Properties();
// connecting to db
try {
//replacing Class.forName("org.postgresql.Driver");
param.put("user",user); param.put("password",pwd);
c = DriverManager.getConnection(dbURL, param);
st= c.createStatement();
System.out.println("Connected to database successfully");
/*
String table = "CREATE TABLE dept5( " +
"DEPTNO mediumint(2 ) NOT NULL,\n" +
"DNAME char(14) DEFAULT NULL, LOC char(13) DEFAULT NULL,\n" +
"PRIMARY KEY (DEPTNO) \n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8";
st.executeUpdate(table);
System.out.println("Created to table dept5 successfully");
c.setAutoCommit(false);
// inserting data in the table
st.executeUpdate("INSERT INTO DEPT5 VALUES (10,'ACCOUNTING','NEW YORK');");
st.executeUpdate("INSERT INTO DEPT5 VALUES (20,'RESEARCH','DALLAS');");
st.executeUpdate("INSERT INTO DEPT5 VALUES (30,'SALES','CHICAGO');");
st.executeUpdate("INSERT INTO DEPT5 VALUES (40,'OPERATIONS','BOSTON');");
//commit all insertion/transaction
c.commit();
// autocommit will treat above as a single transaction
c.setAutoCommit(true);
* System.out.println("Data inserted in table dept5");
* * */
rs = st.executeQuery("SELECT * FROM dept5");
while(rs.next())
{
int dept = rs.getInt("DEPTNO");
String name = rs.getNString("DNAME");
String place = rs.getNString("LOC");
System.out.println("deptno " + dept + " name "+
name + "\r \t" + " place " + place);
}
} catch (SQLException ex) { ex.getErrorCode();
String message = ex.getMessage();
System.out.println(message);
} finally {
System.out.println("going through final block");
try {
if (st== null || st.isClosed()) {
} else {
st.close();
}
if (c != null && !c.isClosed()) {
c.close(); }
} catch (SQLException ex) { ex.getErrorCode();
ex.getMessage();
}
}
System.out.println("dis-Connected to database successfully");
// st.close(); con.commit();con.close();
}
// main block ends here
}
|