टेबल और डेटा
mysql> create table demo87 (name varchar(20), age int);
mysql> insert into demo87 values('John',21), ('David',23), ('Bob',22);
Java कोड: ResultSet से HashMap में डेटा
import java.sql.*;
import java.util.*;
import com.mysql.jdbc.Statement;
public class TableValuesDemo {
public static void main(String[] args) {
Connection con = null;
Statement statement = null;
try {
HashMap hm = new HashMap<>();
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
statement = (Statement) con.createStatement();
String sql = "select * from demo87";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
hm.put(resultSet.getString("name"), resultSet.getInt("age"));
}
System.out.println(hm); // {Bob=22, John=21, David=23}
} catch (Exception e) { e.printStackTrace(); }
}
}
आउटपुट
{Bob=22, John=21, David=23}
मुख्य बिंदु: ResultSet.next() पंक्ति दर पंक्ति बढ़ता है; getString()/getInt() कॉलम मान पढ़ते हैं।