如何使SQL连接语句通用

sin*_*mal 4 java mysql sql

我必须在同一个类的不同方法中执行几个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();
Run Code Online (Sandbox Code Playgroud)

Hus*_*ri' 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;
    }
Run Code Online (Sandbox Code Playgroud)