CREATE DATABASE mydatabase; USE mydatabase; CREATE TABLE customers ( customerID varchar(8) primary key, name varchar(40) default NULL, phone varchar(16) default NULL ); INSERT INTO customers VALUES ('ADDIFK01','Frank Addinsell', '(718) 555-3911'); INSERT INTO customers VALUES ('ALBIBB01','Bob Albinoni', '(213) 555-7566');在这段代码中package homework7_二_1_20221548; import java.sql.*; import javax.swing.JOptionPane; public class Demo { public static void main(String args[]) { String url = "jdbc:mysql://127.0.0.1:3306/student"; String user = "root", pwd = ""; Connection con; Statement sql; ResultSet rs; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("test" + e); } try { con = DriverManager.getConnection(url, user, pwd); sql = con.createStatement(); String sqlStatement; sqlStatement = "SELECT * From message order by height desc"; rs = sql.executeQuery(sqlStatement); while (rs.next()) { double customerID = rs.getDouble("customerID"); String name = rs.getString("name"); double phone = rs.getDouble("phone"); System.out.println(customerID + " " + name + " " + phone); } con.close(); } catch (SQLException e) { System.out.println("数据库操作失败" + e); } } }为什么输不出结果?
时间: 2024-02-14 18:10:56 浏览: 67
这段代码中的 SQL 语句是查询 message 表,但是在数据库中并没有创建名为 message 的表,而是创建了一个名为 customers 的表。因此,需要将 SQL 语句修改为查询 customers 表,同时查询的列名也需要修改为该表中的列名。另外,由于 phone 列的数据类型是 varchar,因此无法直接使用 getDouble() 方法获取,需要改为使用 getString() 方法获取,并且在输出时需要将字符串转换为 double 类型。修改后的代码如下:
```
package homework7_二_1_20221548;
import java.sql.*;
import javax.swing.JOptionPane;
public class Demo {
public static void main(String args[]) {
String url = "jdbc:mysql://127.0.0.1:3306/mydatabase";
String user = "root", pwd = "";
Connection con;
Statement sql;
ResultSet rs;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("test" + e);
}
try {
con = DriverManager.getConnection(url, user, pwd);
sql = con.createStatement();
String sqlStatement;
sqlStatement = "SELECT * From customers order by name";
rs = sql.executeQuery(sqlStatement);
while (rs.next()) {
String customerID = rs.getString("customerID");
String name = rs.getString("name");
String phone = rs.getString("phone");
System.out.println(customerID + " " + name + " " + Double.parseDouble(phone));
}
con.close();
} catch (SQLException e) {
System.out.println("数据库操作失败" + e);
}
}
}
```
注意,这段代码中的查询语句按照客户姓名升序排列,如果需要按照其他列排序,可以修改 SQL 语句中的 "order by" 子句。
阅读全文