I have a methode here which should get data from my preset database. The table has set info in it already. But I can not retrieve the data from the table in my java program. The rest of the code works fine like al the setters and getters. I have an other methode which writes to a specific row in the database. This works fine so I know that there is a connection between eclipse and my database.
What I have :
public void readCard(int id){
try{
java.sql.Statement statement=con.connection.createStatement();
this.id=id;
String gget;
gget= "SELECT DISTINCT * FROM addresscard WHERE (id = \""+
this.id +"\");";
ResultSet rs= statement.executeQuery(gget);
rs.next();
this.id= rs.getInt(1);
this.name= rs.getString(2);
this.adress= rs.getString(3);
this.postcode= rs.getString(4);
this.place= rs.getString(5);
this.telephone= rs.getString(6);
System.out.println(this.id);
}catch(Exception e){
System.out.println(" did not read anything");
}
I put
String gget= "SELECT DISTINCT * FROM adreskaart WHERE (id = \""+
this.id +"\");";
in mysql as:
SELECT DISTINCT * FROM adreskaart WHERE id =2;
The row which corresponds with id 2 get selected. So my database works fine. My guess is that my sql code in eclipse is wrong. Can anyone see why I can't read from the database.
Many Thanks
edit In my changeCard() I should be able to adjust data in my tester class like : Connectie con= new Connectie(); AddressCard ac=new AddressCard();
ak.readCard(2);
ak.setName("prof dr ir P chimp");
ak.changeCard();
Vector tabel;
tabel=ak.readAllCards();
and of course all the gui good stuff here.
public void changeCard(){
try{
java.sql.Statement statement= con.connection.createStatement();
String sset;
sset= "UPDATE adresKaart " + " SET naam = '" + this.naam + "', " + "adres='" + this.adres + "'," +
" postcode='" + this.postcode + "'," + "plaats='" + this.plaats + "'," + "telefoon='" + this.telefoon
+ "' " + " WHERE adreskaart.id = " + this.id;
statement.executeUpdate(sset);
}catch(Exception e){
System.out.println(" did not change anything");
e.printStackTrace();
}
}
Seems that I have the sql wrong but cant seem to figure it out. Thanks in advance .
2 Answers 2
First of all, make sure about your table name. Is it addresscard or adreskaart?
As you wrote, your query should be
SELECT DISTINCT * FROM addresscard WHERE id = 2
but, now it is (extra quotes)
SELECT DISTINCT * FROM addresscard WHERE id = "2"
If you store id as an integer, you should not put those quotes. If id is stored as varchar then you should. Moreover, no need to put semicolon at the end of the query. Try following.
gget= "SELECT DISTINCT * FROM addresscard WHERE id = " + this.id;
3 Comments
I think your slq get a result of arry.So,you should viste the result:
while(rs.next()){
this.id= rs.getInt(1);
this.name= rs.getString(2);
this.adress= rs.getString(3);
this.postcode= rs.getString(4);
this.place= rs.getString(5);
this.telephone= rs.getString(6);
}