日期:2014-05-20 浏览次数:20725 次
import java.sql.*; import javax.swing.JOptionPane; public class ConnectDB{ public void connectData() { Connection con = null; Statement st = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=E:\\EclipseWS\\AddressList\\source\\DB.mdb"; con = DriverManager.getConnection(url,"amin","admin"); st = con.createStatement(); //如何把这个获得的st传给同一工程下的另外一个 //类login,ResultSet rs = st.excuteQuery(""); //来获取数据库的用户名。 }catch(Exception ex) { JOptionPane.showMessageDialog(null , "数据库连接错误"+"SQL exception:" + ex.getMessage() , "Error" , JOptionPane.ERROR_MESSAGE); } } }
import java.sql.*; import javax.swing.JOptionPane; public class ConnectDB{ private Connection con=null; private Statement st=null; public void connectData() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=E:\\EclipseWS\\AddressList\\source\\DB.mdb"; con = DriverManager.getConnection(url,"amin","admin"); st = con.createStatement(); //如何把这个获得的st传给同一工程下的另外一个 //类login,ResultSet rs = st.excuteQuery(""); //来获取数据库的用户名。 }catch(Exception ex) { JOptionPane.showMessageDialog(null , "数据库连接错误"+"SQL exception:" + ex.getMessage() , "Error" , JOptionPane.ERROR_MESSAGE); } } public statement getSt(){ return st; } } [code=Java]
------解决方案--------------------
可以用个简单的工厂模式
public class ConnectDB{ private Connection con=null; private Statement st=null; private String url; static { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=E:\\EclipseWS\\AddressList\\source\\DB.mdb"; } public static Connection createConnection() { try { con = DriverManager.getConnection(url,"amin","admin"); return con }catch(Exception ex) { JOptionPane.showMessageDialog(null , "数据库连接错误"+"SQL exception:" + ex.getMessage() , "Error" , JOptionPane.ERROR_MESSAGE); } } }