【发布时间】:2016-10-31 02:04:30
【问题描述】:
我只需要澄清以下设计是否违反了面向对象设计的最佳实践(与实现 MySQL 数据库有关)。这不是Java EE 规模,而是本科二年级的工作,我在 Oracle 的教程中能找到的只是使用 Java 的大型数据库的设计指南,例如 Data Access Object
我有一个类处理加载JDBC driver 和MySQL Database。它具有定义为static 的Connection 和Statement 对象
/** Enables a connection to the chessleaguedb MySQL database
* @author Erdi Rowlands
*/
public class DatabaseConnection
{
private Console console; // needed for relevant method to mask console input
private Scanner keyboard; // reads user input
private String user; // MySQL user account
private String pass; // MySQL account password
private String host; // MySQL host
static Connection conn; // application needs to communicate with JDBC driver
static Statement st; // issuing commands against the connection is reqiured
/* When instantiated the JDBC driver attempts to load */
public DatabaseConnection()
{
this.loadDriver();
}
public void loadDriver()
{
try
{
Class.forName ("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System.out.println("Could not load the driver");
}
}
public void connectToDatabase()
{
try
{
this.readLogin();
// prompts user to enter login info to console
this.conn = DriverManager.getConnection
("jdbc:mysql://"+host+":3306/chessleaguedb", user, pass);
System.out.println("\nSuccessfully connected to database: "
+ "'chessleaguedb'");
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
我有一个用于创建和填充数据库表的类:
/** Enables the creation and population of the MySQL database 'chessleaguedb' tables
* @author Erdi Rowlands
*/
public class DatabaseTables
{
public DatabaseTables()
{
}
public void createPlayerTable()
{
try
{
DatabaseConnection.st = DatabaseConnection.conn.createStatement();
DatabaseConnection.st.executeUpdate("CREATE TABLE IF NOT EXISTS"
+ "(PlayerName VARCHAR(30)PRIMARY KEY,"
+ "DateOfBirth DATE,"
+ "FIDERating tinyint,"
+ "ClubName FOREIGN KEY fk_club(Clubname) REFERENCES club(ClubName)");
// Create Actor table
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我是否通过在第二类中使用那些静态对象来执行数据库命令来破坏 OOD 最佳实践?如果没有,我将继续制作处理存储过程等的类,并且很高兴我没有做错什么。我不想自然地在 main 方法中包含所有内容,并且除了在需要它们的每个类中加载 JDBC driver 和 Connection 之外,看不到任何其他方法(似乎是多余的)。
【问题讨论】:
-
请为您的问题提供一个更具描述性的标题;标题应该引起人们的兴趣,而目前它几乎只有标签。