一、任务详情
- 下载附件中的world.sql.zip, 参考http://www.cnblogs.com/rocedu/p/6371315.html#SECDB,导入world.sql,提交导入成功截图
- 编写程序,查询世界上超过“你学号前边七位并把最后一位家到最高位,最高位为0时置1”(比如学号20165201,超过3016520;学号20165208,超过1016520)的所有城市列表,提交运行结果截图
- 编写程序,查询世界上的所有中东国家的总人口
- 编写程序,查询世界上的平均寿命最长和最短的国
二、作业步骤
1.1安装xampp
1.2导入world sql(PHP管理器)
2.1我的学号为20175301,改为3017530
编写程序,在最高位置1
import java.sql.*;
public classConnectionDemo1 {
public static void main(String[] args) {
Connection con;
Statement sql;
ResultSet rs;
con = GetDBConnection.connectDB("world", "root", "");
if (con == null) {
return;
}
String sqlStr = "select*from city where population>3017530";
try {
sql = con.createStatement();
rs = sql.executeQuery(sqlStr);
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
String countryCode = rs.getString(3);
String district = rs.getString(4);
int population = rs.getInt(5);
System.out.printf("%d ", id);
System.out.printf("%s ", name);
System.out.printf("%s ", countryCode);
System.out.printf("%s ", district);
System.out.printf("%d
", population);
}
con.close();
} catch (SQLException e) {
System.out.println("Error:" + e);
}
}
}
3
查询世界上的所有中东国家的总人口
import java.sql.*;
public class ConnectionDemo {
public static void main(String[] args) {
Connection con;
Statement sql;
ResultSet rs;
con = GetDBConnection.connectDB("world", "root", " ");
if (con == null) {
return;
}
try {
sql = con.createStatement();
rs = sql.executeQuery("select Name,Population from country where Region = 'Middle East'");
int all = 0;
while (rs.next()) {
String name = rs.getString(1);
int population = rs.getInt(2);
System.out.printf("%s国家的人口为%d
", name, population);
all += population;
}
System.out.println("中东国家的总人口为:" + all);
} catch (SQLException e) {
System.out.println("Error:" + e);
}
}
}
4
查询世界上的平均寿命最长和最短的国家
有的国家平均寿命没有,所以需要加一个无的判断
import java.sql.*;
public class ConnectionDemo {
public static void main(String[] args) {
Connection con;
Statement sql;
ResultSet rs;
con = GetDBConnection.connectDB("world", "root", " ");
if (con == null) {
return;
}
try {
sql = con.createStatement();
rs = sql.executeQuery("select Name,LifeExpectancy from country order by LifeExpectancy");
while (rs.next())
{
float num = rs.getInt(2);
String name = rs.getString(1);
while (num == 0)
{
rs.next();
num = rs.getInt(2);
}
name = rs.getString(1);
System.out.println("平均寿命最短的国家为:" + name);
rs.last();
name = rs.getString(1);
System.out.println("平均寿命最长的国家为:" + name);
}
}
catch (SQLException e) {
System.out.println("Error:" + e);
}
}
}
三、码云链接
https://gitee.com/ShengHuoZaiDaXue/20175301/tree/master/20175301/20175301