package roseindia.net;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;

public class JdbcDataSourceExample implements DataSource {
	Connection connection = null;

	@Override
	public Connection getConnection() throws SQLException {
		if (connection != null) {
			System.out.println("Cant craete a Connection");
		} else {
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/student", "root", "root");
		}
		return connection;
	}

	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		if (connection != null) {
			System.out.println("Cant craete a Connection");
		} else {
			connection = DriverManager.getConnection(
					"jdbc:mysql://192.168.10.13:3306/student", username,
					password);
		}
		return connection;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		PrintWriter logWriter = null;
		try {
			logWriter = new PrintWriter("C:/work/vinay/Logfile.log");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return logWriter;
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub
		try {
			DriverManager.setLogWriter(new PrintWriter(
					"C:/work/vinay/Logfile.log"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	public static void main(String[] args) throws SQLException {
		JdbcDataSourceExample ds = new JdbcDataSourceExample();
		Connection connection = ds.getConnection();
		PrintWriter out = DriverManager.getLogWriter();
		ds.setLogWriter(out);
		PrintWriter res = ds.getLogWriter();
		System.out.println(res.toString());
		Statement stmt = connection.createStatement();
		ResultSet rs = stmt.executeQuery("SELECT * FROM student");
		while (rs.next()) {
			System.out.println("Roll No-" + rs.getInt(1) + ", Name- "
					+ rs.getString(2));
		}
		ds.setLoginTimeout(5);
	}
}