0

我有一个连接数据库的函数,我有一个代码,我在组合框中有一个选择和显示元素,所以我想传递类 connexion.java 组合框 selectedItem 因为它包含我拥有的所有数据库,所以我想要classe connexion 是动态的,所以传递在这个类中选择的元素我不知道我该怎么做,请帮助我

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; 
}  
}
4

3 回答 3

0

A JComboBox accepts any kind of object, so you can simply do something like this.

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

And to retreive the value:

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

However in your Connection class you must override the toString() function, because this is used to display the box.

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

So you can instantiate a connection representing the connection that you want, and when the user selects an item from the combobox, you will have the connection it represents.

于 2013-06-12T14:00:40.023 回答
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(); } }
     */

}
于 2013-06-12T14:01:29.530 回答
0

据我了解,您有 2 个类.. 一个 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; 
}  
}
于 2013-06-12T16:03:19.160 回答