简体   繁体   English

如何从SQL数据库检索数据?

[英]How do I retrieve data from SQL database?

So here is my connection. 这是我的联系。 It successfully works. 它成功地工作。

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection c = DriverManager.getConnection("jdbc:mysql://localhost/Gear?user=root&password=admin");
Statement st = c.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Weapons");
ResultSetMetaData md = rs.getMetaData();

Here is my code to retrieve the data. 这是我的检索数据的代码。

String[] columns = new String[] { "Id", "Name", "Style", "DPS"};    
int rowcount = 0;

if (rs.last()) //finds out how many rows there are
{
  rowcount = rs.getRow();
  rs.beforeFirst();
}

String[][] data = new String[rowcount][columns.length]; //data storage array

while(rs.next())
{
    for( int i = 0; i < rowcount; i++)
    {
        for( int j = 1; j <= md.getColumnCount();j++)
        {
            System.out.println(data[i][j] = rs.getString(j)); //add the record
        }
    }
}

Here is my table data: 这是我的表格数据:

ID, Weapon Name, Style, DPS ID,武器名称,样式,DPS

1, Noxious Staff, Magic, 1000 1,有害人员,魔法,1000

2, Ascension Crossbow, Ranged, 1200 2,提升Cross,远程1200

3, Tetsu Katana, Melee, 950 3,近战片假名Tetsu Katana,950

I'm getting an error saying that it is ArrayIndexOutOfBoundsException out of bounds. 我收到一条错误消息,说它是ArrayIndexOutOfBoundsException超出范围。 How do I fix this error? 如何解决此错误?

The issue might be the way you are grabbing the column value. 问题可能是您获取列值的方式。 When you ask for it, you need to provide the name of the column, not an index numerical value. 要求时,需要提供列名,而不是索引数字值。

Like this: rs.getString("Id") 像这样: rs.getString("Id")

Just do this multiple times to get each column value in the rows. 只需多次执行此操作即可获取行中的每个列值。 Hope this helps! 希望这可以帮助!

You should use the following code 您应该使用以下代码

for( int j = 0; j < columns.length;j++)
    {
        System.out.println(data[i][j] = rs.getString(j + 1)); //add the record
    }

While looking at your code i don't get the point of using metadata . 在查看您的代码时,我不明白使用元数据的意义 You don't need to use it at all. 您根本不需要使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM