无法通过循环打印输出,不知道如何打印第二个表

时间:2016-02-16 16:30:44

标签: java sql netbeans

编辑:一切都会有所帮助。如果有人能告诉我这个过程,至少我会很感激。

我试图让我的代码读取我创建的访问数据库。在该数据库中有2个表,一个是Soccer_Team,另一个是Soccer_Players。我有一个问题,想知道如何让字段名称显示在实际数据前面。当我运行代码时,我得到了这个:

姓名:位置:主场球场:巴塞罗那足球俱乐部西班牙诺坎普球场 名称:位置:主场球场:拜仁慕尼黑德国安联球场

我想要"姓名:"接下来是俱乐部名称,等等...我不熟悉Java,所以我在这里有点困惑。

另外,我想通过SQL查询从我的数据库打印第二个表,它显示上面的内容,但每行下面都打印了播放器信息......我甚至不知道从哪里开始做那。我不确定我是否能很好地解释这一点,如果我让人困惑,我很抱歉。

很抱歉,如果这是要求太多,但我很失落...感谢您的帮助。

package msjavaaccessdb;

import java.sql.*;
import java.util.*;

public class MSjavaAccessDB {

/** Creates a new instance of databaseApplication */
public MSjavaAccessDB() {
}

/**
 * @param args the command line arguments
 */
static String nameOfJdbcOdbcDriver =
            "sun.jdbc.odbc.JdbcOdbcDriver";
//  static String dataBaseNameDSN = "jdbc:odbc:myDataSource";

static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String userName = "";
static String passwordForUser = "";

static Connection myConnectionRequest = null;
static Statement myStatementObject = null;
static ResultSet myResultTuples = null;
static ResultSetMetaData myResultTuplesMetaData = null;

static String queryToBeExecuted = "select * from Soccer_Team";


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

  try {

    //Identify the driver to use
    Class.forName(nameOfJdbcOdbcDriver);

    //Attempt a connection to database...
    Connection myConnectionRequest =
            DriverManager.getConnection(
                    dataBaseNameDSN, userName, passwordForUser);

    //Create a statement object, use its method to execute query
    Statement  myStatementObject =
            myConnectionRequest.createStatement();

    //Use statement object method to execute a query.
    //Hold results in a resutl set...like a cursor
    ResultSet myResultTuples = myStatementObject.executeQuery
                                    (queryToBeExecuted);

    //Call metadata to get the number of attributes
    myResultTuplesMetaData = myResultTuples.getMetaData();
    int numberOfAttributes =
            myResultTuplesMetaData.getColumnCount();
    System.out.println(Integer.toString(numberOfAttributes));

    //For each row in result set, print ALL columns

    for(int rowNum = 1; myResultTuples.next(); rowNum++) {
            for (int i = 1; i <= numberOfAttributes; i++) {
                   if ( (i != 1) ) System.out.print (
                            myResultTuples.getString(i) + "\t");
                   else {//String xyz = myResultTuples.getString(1);    
                        int xyz = Integer.parseInt( myResultTuples.getString(1));

                        System.out.print ("Name: ");
                        System.out.print ("Location: ");
                        System.out.print ("Home Stadium: ");
                   }
            }

            System.out.println("\n\n");
    }

  }  // end of try block

  //handle ALL exceptions to above database calls
  catch (SQLException sqlError) {
    System.out.println("Unexpected exception : " +
            sqlError.toString() + ", sqlstate = " +
            sqlError.getSQLState());
    sqlError.printStackTrace();
  }

}  // end of main method of this class

}  // end of the class

2 个答案:

答案 0 :(得分:0)

所以我不知道你的数据表看起来如何,但我想你想要做的是打印列标签,然后打印行的相应数据值。

for(int rowNum = 1; myResultTuples.next(); rowNum++) {
            for (int i = 1; i <= numberOfAttributes; i++) {
                   //print column label
                   System.out.print(myResultTuplesMetaData.getColumnLabel(i) + ": ");
                   //print data value
                   System.out.print(myResultTuples.getString(i) + "\t");
            }
            System.out.println("\n\n");
            //process SQl-Query about players and print out results in another for loop HERE
}

因此对于第二个表,你必须像SELECT * FROM table2 WHERE team IS (?)那样做PreparedStatement并在另一个循环中打印出结果。

答案 1 :(得分:0)

我现在无法收到错误,因为此时我无法访问NetBeans。当我在家用电脑上时,我可以稍后更新。我不确定我做了什么是有道理的,因为我不知道Java的规则是什么......希望这不是中风诱导。

package msjavaaccessdb;

import java.sql.*;
import java.util.*;

public class MSjavaAccessDB {

/** Creates a new instance of databaseApplication */
public MSjavaAccessDB() {
}

/**
 * @param args the command line arguments
*/
static String nameOfJdbcOdbcDriver =
        "sun.jdbc.odbc.JdbcOdbcDriver";
static String dataBaseNameDSN = "jdbc:odbc:myDataSource";

static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String userName = "";
static String passwordForUser = "";

static Connection myConnectionRequest = null;
static Statement myStatementObject = null;
static ResultSet myResultTuples = null;
static ResultSetMetaData myResultTuplesMetaData = null;
static ResultSet ResultTuples = null;
static ResultSetMetaData ResultTuplesMetaData = null;

static String queryToBeExecuted = "select * from Soccer_Team";
static string secondQuery = "select * from Soccer_Player where team is (?)";


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

try {

//Identify the driver to use
Class.forName(nameOfJdbcOdbcDriver);

//Attempt a connection to database...
Connection myConnectionRequest =
        DriverManager.getConnection(
                dataBaseNameDSN, userName, passwordForUser);

//Create a statement object, use its method to execute query
Statement  myStatementObject =
        myConnectionRequest.createStatement();

//Use statement object method to execute a query.
//Hold results in a resutl set...like a cursor
ResultSet myResultTuples = myStatementObject.executeQuery
                                (queryToBeExecuted);
ResultSet ResultTuples = myStatementObject.executeQuery
                (secondQuery);

//Call metadata to get the number of attributes
myResultTuplesMetaData = myResultTuples.getMetaData();
int numberOfAttributes =
        myResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numberOfAttributes));


ResultTuplesMetaData = ResultTuples.getMetaData();
int numOfAttributes =
        ResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numOfAttributes));


//For each row in result set, print ALL columns

for(int rowNum = 1; myResultTuples.next(); rowNum++) {
        for (int i = 1; i <= numberOfAttributes; i++) {
               //print column label
               System.out.print(myResultTuplesMetaData.getColumnLabel(i) +         ": ");
               //print data value
               System.out.print(myResultTuples.getString(i) + "\t");
        }
        System.out.println("\n\n");
}

for(int rowNum = 1; ResultTuples.next(); rowNum++) {
        for (int i = 1; i <= numOfAttributes; i++) {
               //print column label
               System.out.print(ResultTuplesMetaData.getColumnLabel(i) + ": ");
               //print data value
               System.out.print(ResultTuples.getString(i) + "\t");
        }
        System.out.println("\n\n");
  }
}  // end of try block

//handle ALL exceptions to above database calls
catch (SQLException sqlError) {
  System.out.println("Unexpected exception : " +
        sqlError.toString() + ", sqlstate = " +
        sqlError.getSQLState());
    sqlError.printStackTrace();
  }

}  // end of main method of this class

}  // end of the class