在其他类Java中使用数据库连接

时间:2014-08-19 11:04:06

标签: java mysql connection

我是java开发的新手,我需要一些帮助。我读到我可以使用单例类来建立与数据库的连接。我做了这个单例连接,但我已经不知道如何在其他类中使用这个类了。 这是我的联系:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SingletonDBConnection {

private static SingletonDBConnection instance = null;
private static Connection conn;

private SingletonDBConnection() {

    String url = "jdbc:mysql://localhost:3306/database";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root"; 
    String password = "MyNewPassword";
        try {
                Class.forName(driver);
                conn = DriverManager.getConnection(url,userName, password);
                }

                    catch(ClassNotFoundException cnfErr)
                    {cnfErr.printStackTrace();
                    }
                    catch(SQLException err)
                    {err.printStackTrace();
                    }
}


public static SingletonDBConnection getInstance() {
if(instance == null)
return new SingletonDBConnection();
else
return instance;
}

public static Connection getConnection() {
    return conn;
}
}    

现在我如何在其他类中使用此连接?

另一类应该是例如:

public class statement1 {
String sql = "CREATE TABLE test1 (test2 Integer)";
PreparedStatement pmst = conn.prepareStatement (sql);
rs = pmst.execute();
}

1 个答案:

答案 0 :(得分:0)

// create and get instance of your Singleton
// then retrieve connection initialized in its private constructor
Connection conn = SingletonDBConnection.getInstance().getConnection();
PreparedStatement pmst = conn.prepareStatement(sql);
...