我试图输入城市名称,如果数据库中存在城市名称(否则错误消息),然后我想打印选定的城市名称、人口、纬度和经度。其余代码运行良好。数据库图片在这里public static void city(){ ResultSet rs = null; Scanner k = new Scanner (System.in); System.out.println("Enter the name"); String Name = k.nextLine (); try { rs = stmt.executeQuery("SELECT * FROM cities WHERE name ="+Name); // At least a record selected if(rs.isBeforeFirst ()){ //Iterates through each record while (rs.next ()){ String name = rs.getString (i:1); int population = rs.getInt(i:2); double latitude = rs.getDouble (i:3); double longitude = rs.getDouble(i:4); System.out.println("Name: " + name); System.out.println("Population: " + population); System.out.println("Latitude: " + latitude); System.out.println("Longitude: " + longitude); System.out.println(); } } else { System.out.println("No records selected."); } } catch(SQLException e) { System.out.println("Error selecting from table: " + e.getMessage()); } finally { try { rs.close(); } catch(Exception e) { //ResultSet still null/nothing to close } } }
3 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
这将检查您的数据库中是否有城市名称
rs = stmt.executeQuery("SELECT * FROM cities WHERE name = '"+name+"'");
if(rs.next()){
//it exist
//print record
}
else{
//it does not exist
System.out.println("Error Message!");
}
您还可以使用PreparedStatement您的查询来代替上面的查询。
PreparedStatement p = yourConnection.prepareStatement("SELECT * FROM cities WHERE name = ?");
p.setString(1, name);
rs = p.executeQuery();
子衿沉夜
TA贡献1828条经验 获得超3个赞
看起来好像缺少引号,请尝试以下操作:
rs = stmt.executeQuery("SELECT * FROM cities WHERE name = '"+Name+"' ");
慕虎7371278
TA贡献1802条经验 获得超4个赞
首先,如果字段“名称”是字符变化或文本,则必须像这样修改第 8 行:
rs = stmt.executeQuery("SELECT * FROM cities WHERE name ='"+Name+"'");
添加回答
举报
0/150
提交
取消