我正在使用mysql java连接器。我需要java在不同的步骤中显示第一列和第二列的内容。我如何实现这一目标?
String qry = "select col1,col2 from table1";
Resultset rs = statement.executeQuery(qry);
答案 0 :(得分:4)
我在下面发布了一个示例:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
(来自:http://www.kitebird.com/articles/jdbc.html#TOC_5)
编辑:重新阅读问题并认为您可能意味着您希望稍后在代码中引用一个列,而不是像上面的示例中那样在inital循环中引用。在这种情况下,您可以创建一个数组并稍后引用该数组,或者,如另一个答案所示,您可以只执行另一个查询。
答案 1 :(得分:0)
将它们加载到您选择的任何数据结构中,然后将它们显示在您心中的内容中。
List<String> firstCol = new ArrayList<String>();
List<String> secondCol = new ArrayList<String>();
while(rs.next()){
firstCol.add(rs.getString("col1"));
secondCol.add(rs.getString("col2"));
}
然后您可以根据需要使用两个列表进行操作。
答案 2 :(得分:0)
你可以这样做:
String sql = "select col1,col2 from table1";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) System.out.println(rs.getString("col1"));
答案 3 :(得分:0)
怎么样......(在这里插入鼓):
String qry1 = "select col1 from table1";
Resultset rs1 = statement.executeQuery(qry);
String qry2 = "select col2 from table1";
Resultset rs2 = statement.executeQuery(qry);
(您可能希望更清楚地表达您的问题。)
答案 4 :(得分:0)
我正在使用以下代码:
Statement sta;
ResultSet rs;
try {
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM TABLENAME");
while(rs.next())
{
Id = rs.getString("COLUMN_Name1");
Vid = rs.getString("COLUMN_Name2");
System.out.println("\n ID : " + Id);
System.out.println("\n VehicleID: " + Vid);
}
}
catch(Execption e)
{
}
此代码100%正常运行。
答案 5 :(得分:0)
String emailid=request.getParameter("email");
System.out.println(emailid);
rt=st.executeQuery("SELECT imgname FROM selection WHERE email='emailid'");
System.out.println(rt.getString("imgname"));
while(rt.next())
{
System.out.println(rt.getString("imgname"));
finalimage=rt.getString("imgname");
}