2013-06-12 52 views
0

我有一個函數連接到數據庫 ,我有一個代碼,我有一個選擇和顯示元素在一個combobox中 所以我想傳遞類connexion.java combobox selectedItem因爲它包含所有的數據庫,我有 ,所以我想塔CLASSE的Connexion是動態的,所以通過對 我不此類選擇的元素「知道我怎麼能做到這一點,請幫助我使用combobox selectedItem函數

public class Connexion { 
    private static Connection conn; 

    {  
      try { 
Class.forName("com.mysql.jdbc.Driver"); 
} catch (ClassNotFoundException ex) { 
      Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);} 

      try { 
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456"); 
} catch (SQLException ex) { 
      Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }   
       } 
public static Connection getconx() 
{ 
    return conn; 
} 
} 
+3

我讀的問題三次,可是我還是不知道你在問什麼。我建議你從添加點和大寫字母開始,使其更具可讀性。您還提到了一個組合框,但是它沒有顯示在您發佈的代碼中。總之,更清楚你實際要求的是什麼 – Robin

+1

除了羅賓的建議之外,考慮發佈一個格式良好且正確縮進的代碼。爲了更好的幫助,請儘快發佈[SSCCE](http://sscce.org) –

+0

Okey對不起,因爲我說得不太好英語 –

回答

0

一個JComboBox接受任何形式的的物體,所以你可以簡單地做這樣的事情。

Connection con = new Connection(); 
JComboBox box = getBox(); 
box.addItem(con); 

而中檢索值:

JComboBox box = getBox(); 
Connection con = (Connection)box.getSelectedItem(); 

但是在連接類,你必須覆蓋toString()功能,因爲這是用於顯示框。

class Connection 
{ 
    public String toString() 
    { 
     return "BoxItemDisplayvalue"; <--- here you must put something meaningfull which is displayed in the box. 
    } 
} 

所以,你可以實例表示您希望連接的連接,並且當用戶選擇從組合框的項目,你將有代表的連接。

+0

我想在這裏補充則selectedItem的可變公共靜態連接getconx(字符串質數據庫) { 返回康涅狄格州; } –

+0

Okey,但他告訴我有關getBox()的錯誤 –

+0

Connection conn = Connexion.getconx(); String box = jComboBox1.getActionCommand(); –

0

使用這個類

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 

import javax.naming.NamingException; 

import org.apache.commons.dbcp.BasicDataSource; 

import sun.jdbc.rowset.CachedRowSet; 

public class SQLConnection { 

    private static Connection con = null; 

    private static BasicDataSource dataSource; 


    //we can enable and disable connection pool here 
    //true means connection pool enabled,false means disabled 
    private static boolean useConnectionPool = true; 

    private static int count=0; 

    private SQLConnection() { 

     /* 
     Properties properties = new Properties(); 
     properties.load(new FileInputStream("")); 
     maxActive = properties.get("maxActive"); 
     */ 
    } 

    public static String url = "jdbc:mysql://localhost:3306/schemaname"; 
    public static String password = "moibesoft"; 
    public static String userName = "root"; 
    public static String driverClass = "com.mysql.jdbc.Driver"; 
    public static int maxActive = 20; 
    public static int maxIdle = 10; 

    private static final String DB_URL = "driver.classs.name"; 
    private static final String DB_USERNAME = "database.username"; 
    static { 
    /*Properties properties = new Properties(); 
     try { 
     properties.load(new FileInputStream("D:\\CollegeBell\\properties\\DatabaseConnection.properties")); 
      //properties.load(new FileInputStream("E:\\vali\\CollegeBell\\WebContent\\WEB-INF")); 
      //properties.load(new FileInputStream("D:\\DatabaseConnection.properties")); 
      url = properties.getProperty(DB_URL); 
      System.out.println(url); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }*/ 
     dataSource = new BasicDataSource(); 
     dataSource.setDriverClassName(driverClass); 
     dataSource.setUsername(userName); 
     dataSource.setPassword(password); 
     dataSource.setUrl(url); 
     dataSource.setMaxActive(maxActive); 
     dataSource.setMinIdle(maxIdle); 
     dataSource.setMaxIdle(maxIdle); 

    } 

    //public static Connection getConnection(String opendFrom) throws SQLException, 
    public static Connection getConnection(String openedFrom) { 
     count++; 
      System.out.println("nos of connection opened till now="+count); 
     System.out.println("Connection opended from "+openedFrom); 
    // System.out.println("Connection Opended "); 
     try { 

      if (useConnectionPool) { 
       con = dataSource.getConnection(); 
       System.out.println(dataSource.getMinEvictableIdleTimeMillis()); 
       //dataSource.setMaxWait(15000); 
       System.out.println(dataSource.getMaxWait()); 
       System.out.println(count); 
      } else { 
       Class.forName("com.mysql.jdbc.Driver"); 
       con = DriverManager.getConnection(url, userName, password); 
      } 
     } 

      //System.out.println("Connection : " + con.toString()); 
      catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return con; 
    } 

    public static void closeConnection(Connection con, String closedFrom) 
      { 

     //System.out.println("Connection closed from: " + con.toString()); 
    // System.out.println("Connection closed from: " + closedFrom); 
     //log.info("Connection closed from: " + closedFrom); 
     if(con != null){ 
      count--; 
      System.out.println("Connection count value after closing="+count); 
     System.out.println("Connection closed from: " + closedFrom); 
     try { 
      con.close(); 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     } 
    } 
    //added by nehal 
    public static void closeStatement(Statement ps, String closedFrom) 
    { 
if(ps != null){ 
System.out.println("Statement closed from: " + closedFrom); 
try { 
    ps.close(); 
} catch (SQLException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
} 
} 


    public static void closePreparedStatement(PreparedStatement ps, String closedFrom) 
    { 
if(ps != null){ 
System.out.println("Statement closed from: " + closedFrom); 
try { 
    ps.close(); 
} catch (SQLException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
} 
} 

    public static void closeResultSet(ResultSet rs, String closedFrom) 
    { 
if(rs != null){ 
System.out.println("ResultSet closed from: " + closedFrom); 
try { 
    rs.close(); 
} catch (SQLException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
} 
} 
    //added by nehal 

    /*public static ResultSet executeQuery(String query) throws Exception { 
     Connection con = null; 
     Statement stmt = null; 
     ResultSet rs = null; 
     CachedRowSet crset = null; 
     try { 
      con = getConnection(); 
      stmt = con.createStatement(); 
      rs = stmt.executeQuery(query); 
      crset = new CachedRowSet(); 
      crset.populate(rs); 
     } catch (Exception e) { 
      throw e; 
     } finally { 
      if (rs != null) { 
       rs.close(); 
      } 
      if (stmt != null) { 
       stmt.close(); 
      } 
      if (con != null && !con.isClosed()) { 
       con.close(); 
      } 
     } 
     return crset; 
    } 

    public static int executeUpdate(String query) throws Exception { 
     Connection con = null; 
     Statement stmt = null; 
     ResultSet rs = null; 
     int rows = -1; 
     try { 
      con = getConnection(); 
      stmt = con.createStatement(); 
      rows = stmt.executeUpdate(query); 
     } catch (Exception e) { 
      throw e; 
     } finally { 
      if (rs != null) { 
       rs.close(); 
      } 
      if (stmt != null) { 
       stmt.close(); 
      } 
      if (con != null && !con.isClosed()) { 
       con.close(); 
      } 
     } 
     return rows; 
    } 

    public static boolean execute(String query) throws Exception { 
     Connection con = null; 
     Statement stmt = null; 
     ResultSet rs = null; 
     boolean rowsreturned = false; 
     try { 
      con = getConnection(); 
      stmt = con.createStatement(); 
      rowsreturned = stmt.execute(query); 
     } catch (Exception e) { 
      throw e; 
     } finally { 
      if (rs != null) { 
       rs.close(); 
      } 
      if (stmt != null) { 
       stmt.close(); 
      } 
      if (con != null && !con.isClosed()) { 
       con.close(); 
      } 
     } 
     return rowsreturned; 
    }*/ 

    /* 
    * public static void closeConnection(Connection con) { try { con.close(); 
    * con=null; } catch (SQLException e) { // TODO Auto-generated catch block 
    * e.printStackTrace(); } } 
    */ 

} 
+0

但所選項目的變化而變化,其中與組合框的元素之間的關係 –

+0

使用此連接obj,從數據庫獲取所有值並顯示在組合框中。 –

+0

將項目添加到組合框 –

0

什麼,我明白了,你有2個班.. 一個,你必須與其中u要建立連接的架構名稱的組合框的GUI。 所以你必須讓EventListener在按下提交按鈕時「聽」。

例如:

Connection con = null; 
JButton submitButton = new JButton("Confirm db"); 
submitButton.addActionListener(new MyConnectionListener()); 

.. 
//Could be inner class 
class MyConnectionListener implements ActionListener { 

@Override 
public void actionPerformed(ActionEvent evt){ 
     if(cmb.getSelectedItem() != null){ 
      con = Connection.getConx(cmb.getSelectedItem().toString()); 
     } 

} 

} 

而在你的Connexion類

public class Connexion { 

public static Connection getconx(String schema) 
{ 
Connection conn = null; 
      try { 
Class.forName("com.mysql.jdbc.Driver"); 
} catch (ClassNotFoundException ex) { 
      Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);} 

      try { 
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+schema, "root", "123456"); 
} catch (SQLException ex) { 
      Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }   
       } 


    return conn; 
} 
} 
+0

是感謝的,即使我做的另一種方式,但這些代碼似乎比我雷 –

+0

更好@ cisco.nat考慮接受任何答案,upvoting他們誰幫你 – nachokk