Java数据库不返回值

时间:2015-04-12 14:08:40

标签: java mysql

我正在尝试开发一个简单的程序,询问用户的姓名和电话号码,将其添加到MySQL数据库,然后返回结果。在程序应该打印数据库的结果之前,我已经完成了所有工作。有人可以让我知道我做错了什么吗?

public class ContactList {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://Devry.edupe.net:8300/CunninghamCustomer";

static final String USER = "3508";
static final String PASS = "******";

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    Customer aCustomer = new Customer();

    try{
        Class.forName("com.mysql.jdbc.Driver");

        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        stmt = conn.createStatement();
        String sql;
        sql = "INSERT INTO CUSTOMER (" + aCustomer.getName() + "," + aCustomer.getPhoneNumber() + ")";
        ResultSet rs = stmt.executeQuery(sql);
        rs.close();
        stmt.close();

        stmt = conn.createStatement();
        sql = "SELECT name, phone FROM CUSTOMER";
        ResultSet rs2 = stmt.executeQuery(sql);

        while(rs2.next()) {
            String name = rs2.getString("name");
            String phone = rs2.getString("phone");

            System.out.print("Name: " + name);
            System.out.print(", Phone Number: " + phone);
        }

        rs2.close();
        stmt.close();
        conn.close();

    } catch(SQLException se) {
        se.printStackTrace();

    } catch(Exception e) {
        e.printStackTrace();

    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }

    System.out.println("Complete");
}

}

public class Customer {

String name = "Unknown";
String phoneNumber = "Unknown";
String message = "Contact Added!";

public Customer() {
    getInfo();
}

public void getInfo() {
name = JOptionPane.showInputDialog("Customer Name");
phoneNumber = JOptionPane.showInputDialog("Phone Number");
JOptionPane.showMessageDialog(null, message);
}

public String getName() {
    return name;
}

public String getPhoneNumber() {
    return phoneNumber;
}
}

1 个答案:

答案 0 :(得分:0)

您忘记了插入语句中的values

sql = "INSERT INTO CUSTOMER VALUES(" + aCustomer.getName() + "," + aCustomer.getPhoneNumber() + ")";