In java , jdbc connection is very simple , just add a mysql jar file in lib folder and make special class which return Connection type reference .in this example i'm using properties file to pass user name and password.
This is type 4 driver example bcoz it uses java code to access data from MySql,
public Connection getdbConnection()
{
try { Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException ex) { System.out.println("Error: unable to load driver class!"); System.exit(1); }
String URL = "jdbc:mysql://localhost:3306/
";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Connection conn = DriverManager.getConnection(URL, info);
return conn;
}
Complete Code is here :
import java.io.IOException; import java.sql.*; public class DBUtil { static Connection cn=null; public Connection getConnect() { try { Class.forName("com.mysql.jdbc.Driver"); cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","admin"); } catch(ClassNotFoundException se) { se.printStackTrace(); } catch (SQLException e1) { e1.printStackTrace(); } return cn; } }
No comments:
Post a Comment