gpt4 book ai didi

Java 数据库不返回值

转载 作者:行者123 更新时间:2023-11-29 22:34:39 24 4
gpt4 key购买 nike

我正在尝试开发一个简单的程序,该程序询问用户的姓名和电话号码,将其添加到 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;
}
}

最佳答案

您忘记了插入语句中的

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

关于Java 数据库不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29590325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com