SQL到java 2d矩阵

时间:2018-05-21 21:01:20

标签: java sql

我不明白为什么它正在关闭连接并且没有将结果集中的信息提供给int[][]有人可以帮助我我感谢谢谢

public void InsertBoredFromSQL()
{
    Connection conn = null;
    Statement st = null;
    ResultSet rs1 = null;
    int[][] Arr = new int[8][8];
    String Query = "select A,B,C,D,E,F,G,H from Games where GameID =" + this.res;
    //this is a variable to help from the outside (globale) 

    try
    {
        //crate connection
        conn = getConnection();
        //crate statement and execute query
        st = conn.createStatement();
        rs1 = st.executeQuery(Query);
        //from here it jumps to the exeption and i don't know why it wont run
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                rs1.next();
                char c = 'A';
                char column = (char) (i + c);
                Arr[i][j] = rs1.getInt(column);
            }
        }
    }
    catch (Exception ex)
    {
        System.out.println(ex);
    }
}

1 个答案:

答案 0 :(得分:0)

你的部分问题是:

 char c = 'A';
 char column = (char) (i + c);
 Arr[i][j] = rs1.getInt(column);

您正在使用方法ResultSet#getInt(int),没有方法将char作为参数,因此char会转换为int第一次迭代的情况是A 65

使用从1开始的索引来获取结果集的第一列,或者将列char转换为字符串以按名称获取列。

您可能最好为结果集使用while循环 - 请考虑如果查询返回意外的行数会发生什么。你可以这样做:

while(rs.next())
{
    // Do your row operations
}

这有效,ResultSet#next()将前进到下一行,并根据是否还有其他行返回true或false。

这也会带来你的代码的另一个问题 - 你的rs.next()调用在你的内部循环中 - 这意味着你将为每次迭代推进一行和一列,然后可能会得到一个新的异常。

如果您使用

,也可以从例外中获得更好的细节
catch(Exception ex) {
     ex.printStackTrace()
}