如何将变量从Java类调用到另一个类?

时间:2013-05-22 23:56:24

标签: java mysql

我读过有关继承或使用导入的内容。我只是无法得到正确的答案。首先,我的代码是以下形式:

class queries{
String query1="Select * from "+tableName+";
String query2="Select "+columnName+" from "+tableName+";
}

现在,我有另一个类,我希望使用查询类中提到的查询来进行SQL查询:

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


class test{

public static void main(String args[])throws SQLException
{

try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("This is Wrong");
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connect = DriverManager
  .getConnection("SQLCONNECTION");
PreparedStatement preparedStatement = connect
  .prepareStatement(THIS SHOULD CALL query1 or query2);
 ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
   System.out.println("THIS RUNS");
  //display text
}
preparedStatement.close();
connect.close();
}
}

好吧,我需要弄清楚如何从test中的查询类调用query1或query2。对不起,但我希望有人能帮助我以干净的方式做到这一点。我还可以在查询中创建Hashtable,我根据其名称调用相应的查询。

非常感谢。

1 个答案:

答案 0 :(得分:1)

class queries
{
    public static String getQuery1(String tableName)
    {
        return "Select * from "+tableName;
    }

    public static String getQuery2(String tableName, String columnName)
    {
        return "Select "+columnName+" from "+tableName;
    }
}

然后这样做:

PreparedStatement preparedStatement =
    connect.prepareStatement(queries.getQuery1("INSERT TABLE NAME HERE"));