4

我必须在同一类的不同方法中执行几个 SQL 查询。有什么方法可以使这些语句通用,我可以在所有方法中使用相同的 con,statement 变量来执行查询。

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/kamal","root","root");
Statement statement=con.createStatement();
4

6 回答 6

5

在您的班级中使用此方法并一次又一次地调用它

public Connection getMyConnection() throws ClassNotFoundException, SQLException
    {
        String connectionURL = "jdbc:mysql://localhost:3306/test";
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(connectionURL, "root", "root");
        return con;
    }
于 2013-02-16T20:16:09.270 回答
3

您可以在静态方法中编写连接语句,该方法可以在您的其他类中重用:

public Connection getConnection() throws ClassNotFoundException, SQLException {

    String connURL = "jdbc:mysql://localhost:3306/test";
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(connURL, "username", "password");
    return con;
}

但这有一个缺点,您必须手动管理数据库连接的打开和关闭。

为了缓解上述缺点,可以考虑使用像 Hibernate 这样的对象关系映射框架,它将连接细节抽象到一个设置文件中,该文件将被每个数据库连接重用。

于 2013-02-16T20:13:19.747 回答
1

如果您需要整个类中的变量,您可能希望将其设为成员变量。

但是,不鼓励使用类似的资源Connections,因为它很容易剥夺系统,并增加额外的负载。

您可以做的是使用一种称为Singleton. 在这里阅读。

基本上,您可以创建一个ConnectionManager使用此实现调用的新类

class ConnectionManager {

private static ConnectionManager _instance = null;
private Connection con = null;

protected ConnectionManager() {
    //empty
}

private void init() {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    this.con = DriverManager.getConnection
          ("jdbc:mysql://localhost:3306/kamal","root","root");
}
public Connection getConnection() {
    return this.con;
}

public static ConnectionManager getInstance() {
    if(_instance == null) {
        _instance = new ConnectionManager();
        _instance.init();
    }
    return _instance;
}

}//end class

现在,这对我们有很多帮助,尤其是在您的应用程序是多线程的情况下。我们只需要建立一个连接,除非程序终止,否则它将保持不变。在需要创建新的任何地方Statement,您都可以简单地使用它。

ConnectionManager.getInstance().getConnection().createStatement();
于 2013-02-16T20:15:04.047 回答
1

这是连接池的一个非常幼稚的实现。请注意,这是使用记事本编写的,尚未经过测试:

public interface ConnectionPool {
    public Connection getConnection() throws SQLException;
    public void closeConnection(Connection connection) throws SQLException;
}


public class MySQLConnectionPool implements ConnectionPool {
    private static final Class<?> mysqlDriver;
    private final Stack<Connection> connections;
    private final String url;
    private final String user;
    private final String password;
    private final int maxSize;

    static {
        mysqlDriver = Class.forName("com.mysql.jdbc.Driver");
    }

    public MySQLConnectionPool(String url, String user, String password, int initialSize, int size) {
        if (initialSize > size) {
            throw new IllegalArgumentException("Pool initial size must not be greater than size");
        }
        if (size <= 0) {
            throw new IllegalArgumentException("Pool size must be greater than zero");
        }
        this.size = maxSize;
        this.url = url;
        this.user = user;
        this.password = password;

        this.connections = new Stack<Connection>();
        try {
            for (int i = 0;i < initialSize;i++) {
                connections.push(getConnection(url, user, password));
            }
        } catch (Exception exception) {
            // TODO: Log somewhere?
        }
    }

    public Connection getConnection(String url, user, password) throws SQLException {
        DriverManager.getConnection(url, user, password);
    }

    public Connection getConnection() SQLException {
        try {
            synchronized (connections) {
                return connections.pop();
            }
        } catch (EmptyStackException exception) {
            return getConnection(url, user, password);
        }
    }

    public void closeConnection(Connection connection) throws SQLException {
        synchronized (connections) {
            if (connections.size() < maxSize) {
                connections.push(connection);
                return;
            }
        }
        connection.close();
    }
}


public class SingletonMYSQLConnectionPool extends MySQLConnectionPool() {
    private static volatile SingletonMYSQLConnectionPool instance;

    private SingletonMYSQLConnectionPool() {
        super("jdbc:mysql://localhost:3306/kamal","root","root", 0, 2);
    }

    public static SingletonMYSQLConnectionPool getInstance() {
        if (instance == null) {
            synchronized (SingletonMYSQLConnectionPool.class) {
                if (instance == null) {
                    instance = new SingletonMYSQLConnectionPool();
                }
            }
        }
        return instance;
    }
}
于 2013-02-16T21:13:26.297 回答
0
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
            PrintWriter pw = response.getWriter();
            Connection conn;  
            try
            {
            String fname = request.getParameter("fname");
            String lname = request.getParameter("lname");
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3307/soft\",\"root\",\"root");
            PreparedStatement pst = (PreparedStatement) conn.prepareStatement("insert into soft.IT(fname,lname) values(?,?)");
                pst.setString(1,fname);  
                pst.setString(2,lname);        
                int i = pst.executeUpdate();  
                if(i!=0){  

                    pw.println("<br>Record has been inserted");  
            }  
            else
            {  
                    pw.println("failed to insert the data");  
            }  
            }catch (Exception e)
            {  
                    pw.println(e);  
            }  
        }
于 2017-09-12T16:32:13.547 回答
-1

使它们在您的数据库中存储过程。

于 2013-02-16T20:21:53.430 回答