这是我的代码:
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
if(source == buttonShop)
{
try
{
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database?autoReconnect=true&useSSL=false", "xxx", "xxx");
Statement myStmt = myConn.createStatement();
ResultSet myRs1 = myStmt.executeQuery("select * from shop");
while(myRs1.next())
{
shop += myRs1.getString("ID_SHOP")+" "+myRs1.getString("NAME")+" "+myRs1.getString("ADRESS")+" "+myRs1.getString("PHONE")+"\n";
}
}catch(Exception exc){
exc.printStackTrace();
};
notifyObserver1();
shop = "";
}
else if(source == buttonEmployee)
{
try
{
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database?autoReconnect=true&useSSL=false", "xxx", "xxx");
Statement myStmt = myConn.createStatement();
ResultSet myRs2 = myStmt.executeQuery("select * from employee");
while(myRs2.next())
{
employee += myRs2.getString("ID_EMPLOYEE")+" "+myRs2.getString("ID_SHOP")+" "+myRs2.getString("NAME")+" "+myRs2.getString("SURNAME")+"\n";
}
}catch(Exception exc){
exc.printStackTrace();
};
notifyObserver2();
employee = "";
}
}
这是一个数据库应用程序。我不想将每个Connection myConn = ...和Statement myStmt = ...片段复制粘贴到所有按钮源。如何让它成为全球性的'在行动中可见的执行方法?
答案 0 :(得分:0)
首先你应该有一个Db实用程序说' DBUtil'至少使用getConnection方法的类。 此getConnection应根据您的实现创建连接或从池中返回。
DBUtil Class:
static Connection getConnection()
之后创建两个辅助方法来处理这两个场景,例如:
getEmployeeDetails(){}
getShopDetails(){}
在这些方法中,理想情况下应使用:
try(Connection conn = DBUtil.getConnection();
PreparedStatement st = conn.prepareStatement("Your Qry");
ResultSet rs = st.executeQuery()){
// Do Something
}
一些好点:
您还可以创建一个通用方法,将查询字符串传递给它,执行一些条件处理,然后将最终结果返回给调用者。这种通用方法将处理数据库通信。