我正在製作一個程序,從我創建的數據庫中檢索輸入的數據/字段值。但是當我運行它時,輸出始終爲空。我不知道什麼是錯的?這裏是我的代碼:從java數據庫檢索值
import java.sql.*;
public class GuestsInfo
{
private String firstName, lastName;
private int age;
private Connection con;
private PreparedStatement statement;
public GuestsInfo()
{
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/3moronsdb","root","");
} catch (Exception e) {
e.printStackTrace();
}
}
public GuestsInfo(String firstName, String lastName, int age)
{
this();
try
{
statement = con.prepareStatement("Insert into guest(firstName,lastName,age)values(?,?,?)");
statement.setString(1, firstName);
statement.setString(2, lastName);
statement.setInt(3, age);
statement.executeUpdate();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
public void setFirstName(String firstName)
{
try{
statement= con.prepareStatement("SELECT * FROM guest WHERE firstName = ?");
statement.setString(1, firstName);
ResultSet rs = statement.executeQuery();
while(rs.next()){
firstName = rs.getString(1);
}
}catch(Exception e){
System.out.print(e);
}
}
public String getFirstName(){
return firstName;
}
public void setLastName(String lastName)
{
try{
statement= con.prepareStatement("SELECT * FROM guest WHERE lastName = ?");
statement.setString(2, lastName);
ResultSet rs = statement.executeQuery();
while(rs.next()){
lastName = rs.getString(2);
}
}catch(Exception e){
System.out.print(e);
}
}
public String getLastName(){
return lastName;
}
public void setAge(int age){
try{
statement = con.prepareStatement("SELECT * FROM guest WHERE age=?");
statement.setInt(3, age);
ResultSet rs = statement.executeQuery();
while(rs.next()){
age = rs.getInt(3);
}
}catch(Exception e){
System.out.print(e);
}
}
public int getAge(){
return age;
}
在我的主類,我有這樣的代碼:
public class TestMain {
public static void main(String [] args){
GuestsInfo gi = new GuestsInfo();
gi.setFirstName("Ericka");
System.out.println(gi.getFirstName());
}
}
我不知道爲什麼它總是說空當我運行它。
忽略事情發生的地方,可能性是你沒有「Ericka」存儲在數據庫中的字符串。考慮到你正在提供加載的價值,這也沒有意義。如果你已經知道了,那你爲什麼要打數據庫來加載它? – pickypg
看起來您的GUESS表格沒有「firstName」列中的「Ericka」值。 –
毫米..實際上,我已經在我的主插入了這個:GuestsInfo gi = new GuestsInfo(「Ericka」,「Asi」,18);我的數據庫中有數據。我想要的是從我的數據庫中獲取數據。我怎樣才能做到這一點? – NOOBprogrammer