java - How to put database connection information to a separate file? -
in php, create file, e.g. connect.php
, include file each , every page like:
in java created separate file in same project folder called connect.java
, tried call in other files files database connection no luck far .
i tried last time amazed me variables connect page not able use them in main program . can please me . bellow code use connect mysql , prinde stuff
but wanna make separate file don’t print nothing connect , print want in different file
so if talk in php term wanna include other files connectivity might needed.
try { class.forname("com.mysql.jdbc.driver"); system.out.println("driver loading success!"); string url = "jdbc:mysql://localhost:3306/saloon"; string name = "root"; string password = ""; try { java.sql.connection con = drivermanager.getconnection(url, name, password); system.out.println("connected."); // pull data database java.sql.statement stmts = null; string query = "select userid, username, name , address, hairstyle saloonuser "; stmts = con.createstatement(); resultset rs = stmts.executequery(query); int li_row = 0; while(rs.next()){ mystable.setvalueat(rs.getstring("username"),li_row,0); mystable.setvalueat(rs.getstring("name"),li_row,1); mystable.setvalueat(rs.getstring("address"),li_row,2); mystable.setvalueat(rs.getstring("hairstyle"),li_row,3); int userid = rs.getint("userid"); string username = rs.getstring("username"); string name1 = rs.getstring("name"); system.out.println(name1); li_row++; } } catch (sqlexception e) { e.printstacktrace(); } } catch (classnotfoundexception e) { e.printstacktrace(); } } }
one of way approach have basedao
method returns connection
object, can have following code -
public class basedao { public connection getconnection() { class.forname("com.mysql.jdbc.driver"); string url = "jdbc:mysql://localhost:3306/saloon"; string name = "root"; string password = ""; connection con = drivermanager.getconnection(url, name, password); return con; } }
you can extend basedao
in other dao
classes or create object of basedao
class , connection
object.
your remaining code in separate dao
class. (lets call getdatadao
).
public class getdatadao extends basedao { connection con = getconnection(); statement stmts = null; string query = "select userid, username, name , address, hairstyle saloonuser "; stmts = con.createstatement(); resultset rs = stmts.executequery(query); int li_row = 0; while(rs.next()){ mystable.setvalueat(rs.getstring("username"),li_row,0); mystable.setvalueat(rs.getstring("name"),li_row,1); mystable.setvalueat(rs.getstring("address"),li_row,2); mystable.setvalueat(rs.getstring("hairstyle"),li_row,3); int userid = rs.getint("userid"); string username = rs.getstring("username"); string name1 = rs.getstring("name"); system.out.println(name1); li_row++; } }
Comments
Post a Comment