简体   繁体   中英

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

1, Noxious Staff, Magic, 1000

2, Ascension Crossbow, Ranged, 1200

3, Tetsu Katana, Melee, 950

I'm getting an error saying that it is ArrayIndexOutOfBoundsException out of bounds. 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")

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 . You don't need to use it at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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