我正在写关于软件工程的论文,我正在构建一个使用 SQL 数据库的小型应用程序,在本例中为 MySQL。我也在使用应用程序 Controller 模式。因此,我用于从数据库中检索数据的代码是;
public static void main(String[] args)
{
try
{
String url = "jdbc:mysql://localhost:3306/tm470_returns_stock_management_system";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"root","root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM test_table");
while (res.next())
{
int id = res.getInt("test_id");
String msg = res.getString("test_info");
System.out.println(id + "\t" + msg);
}
con.close();
}
catch(Exception e)
{
System.out.println("DB connection unsuccesful");
}
}
我现在想将它从我的主类/字符串中转移到我的应用程序 Controller 类(称为 Facility)中。
现在我的问题是,对于我的设施类中需要访问数据库的每个方法,我每次都必须执行完整的代码吗?或者我可以在 Facility 类中创建一个方法,每个应用程序方法都可以在需要访问数据库时调用该方法。如果我可以将所有这些浓缩成一个方法,你能告诉我如何去做吗?
请对我温柔一些,我是一个学习者:)
最佳答案
如何添加像 ConnectionUtil 这样的实用程序类并使用静态方法来访问连接。
导入java.sql.Connection; 导入 java.sql.DriverManager;
public class ConnectionUtil{
static final String url = "jdbc:mysql://localhost:3306/";
static final String dbName = "test";
static final String driver = "com.mysql.jdbc.Driver";
static final String userName = "userparatest";
static final String password = "userparatest";
Connection con = null;
static Connection getConnection() throws Exception {
if(con == null)
{ Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + dbName, userName,password);
}
return con;
}
}
这可以进一步改进,但只是提供一个开始..
只要你想要一个声明,就在下面调用..
Statement st = ConnectionUtil.getConnection().createStatement();
关于java - 将 Java 连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29718918/