I use Dbutils to call elements in one table of database
private void showEvent(){
try {
String query="SELECT EventID, MemberID,Description, Date,
Time, Venue, EventTypes FROM formal UNION SELECT EventID,
MemberID,Description, Date, Time, Venue, EventTypes FROM social";
ps = c.prepareStatement(query);
rs=ps.executeQuery();
tbShowEvent.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
Logger.getLogger(ShowEvent.class.getName()).log(Level.SEVERE, null, ex);
}
}
How to delete one element in table when I click the mouse to that element
Illustration: http://i.stack.imgur.com/ib77V.png
add an event listener on your delete button
create your stored procedure code for the delete in the event listener.
after a succesful delete in the DB delete the row in your table in the table Model
refresh you table. Call fireTableDataChanged() on your tableModel
Related
I have defined a custom ListModel as an inner class of some other class holding some data. To populate the ListModel, I query a database file and select the data in it, as shown in the piece of code below. Everything appears nicely in a JList using
this ListModel.
What I don't understand is the "use of unchecked or unsafe operations". When I compile with -Xlint, I get the warning:
"missing type arguments for generic class DefaultListModel<E>"
My questions is what is <E> in the first line of my code below:
public class SalListModel extends DefaultListModel<E=?>{
String defaultSearch="*";
String salName=defaultSearch;
//inner class constructor
public SalListModel(){
try{
//connection creates the database if it does not exist
Class.forName("org.sqlite.JDBC");
Connection c=
DriverManager.getConnection("jdbc:sqlite:"+dbfile);
Statement st=c.createStatement();
String sql;
sql="select "+salName+" from "+tablename+
" ORDER BY "+name[0]+" ASC;"; //alphabetical order
ResultSet rs=st.executeQuery(sql);
while (rs.next()){
addElement(rs.getString(name[0])+" "+rs.getString(cnp[0]));
}
rs.close();
st.close();
c.close();
}
catch (ClassNotFoundException cnfe){
System.out.println("SQL SalListModel class not found: "+
cnfe.getMessage());
}
catch (SQLException sqle){
System.out.println("SalListModel SQL exception:"+
sqle.getMessage());
}
}
}
I have defined a custom ListModel
Why? You are not adding any new functionality to the model. Loading data into a model should not be considered new functionality. Just create a method in your class to load the data into the model. Then your code would be something like:
ListModel<String> model = new DefaultListModel<String>();
addDataToModel( model );
My questions is what is <E> in the first line of my code below:
You are adding String data to the model so you should be using DefaultListModel<String>
I have two table and want both table must update and save altogether otherwise rollback. i am using Transaction but not getting expected result when found runtime exception. Table_1 got updated and table_2 was not updated after getting some conversion issues in my java code.
Service Class
public void startTransaction(){
try{
transaction.begin();
//Calls manager's class method to update and save the data into table
transaction.commit();
}catch(Exceptio e){
transaction.rollback();
}
}
Manager class
public void updateAndSave(){
try{
-> calls DAO method for table_1
->Update Table_1 via DAO update method
-> calls DAO method for table_2
->Update Table_2 via DAO update method
}catch(Exception e){
......
}
}
I am inserting record in database(MySQL) based on user input. Immediate the data is inserted i want to retrieve the record i just inserted and display it in textfield.
But to my surprise nothing is retrieved. Is there some kind of way that will refresh my database immediately i insert data in db. I am using java!
public class Member {
public Member(){
final String nameMember = inputName.getText();
//Button listener action
newAccount.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try {
//this method insert data into db
subscribe();
//this retrieves the data inserted by subscribe()
createdAccountDetails(nameMember);
} catch (SQLException ex) {
Logger.getLogger(Member.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
You have to commit the data into db then only you can fetch it into results. But, it would be a bad practice to use insert and select as two different calls.
Either you can save the values in session and show them(if no exception occurred during insertion) or you can use a pl/sql function or procedure for the same.
I have a Jpanel that contain a JTabel and JTextField that display the value of the Jtable row when the row is clicked twice. the user can edit the JTextField value than click a button to update once the button is click the updateUser method will be called. I am trying to write a JUnit test to test that the updateUser is updating user.
How can I perform double click on a specific table row to get the data displayed in the specified JTextField?
public void updateUser(){
String id= txtid.getText();
String name =txtName.getText();
String q = "UPDATE `user` SET `name`=? WHERE `id`=?";
try{
PreparedStatement ps = Login.con.prepareStatement(q);
ps.setString(2, id);
ps.setString(1, name);
ps.executeUpdate();
JOptionPane.showConfirmDialog(null, "User Updated");
}catch(Exception eu){
}
}
Unittest should test the Unit, specefically the logical unit, in your case i would change the updateUser() method to:
bool updateUser(String id, String name)
which you can test then undependant from the GUI elements.
The showConfirmDialog can then be shown according to the return value of the updateUser method.
Is there a way in spring jdbc to return a composite primary key when a row is inserted.
This composite primary key is made up of values from separate sequences
Any help is greatly appreciated
Regards
Damien
Here is a full example (tested on PostgreSQL 8.4):
My table:
CREATE TABLE test
(
id serial NOT NULL,
otherid serial NOT NULL,
val text,
CONSTRAINT test_pkey PRIMARY KEY (id, otherid)
)
This is how you get keys back:
public void doStuff() {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("insert into test(val) values (?)", Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, 42);
return ps;
}
},
keyHolder);
keyHolder.getKeys().get("id");
keyHolder.getKeys().get("otherid");
}
Now, if you want to get your composite key as an instance of some class directly from keyHolder, it is not simple.
JdbcTemplate uses ColumnMapRowMapper to map generated keys (generated keys are returned as result set, at least on PostgreSQL. It actually returns the whole row as if you were executing select on the row you just inserted). Same ColumnMapRowMapper is used in number of other places in JdbcTemplate.
The only possible point of extension here is KeyHolder itself. Here is what you can do:
public void doStuff() {
CompositeKeyHolder keyHolder = new CompositeKeyHolder();
... same code here ...
keyHolder.getCompositeKey();
}
class CompositeKeyHolder extends GeneratedKeyHolder {
private boolean converted;
public CompositeKey getCompositeKey() {
return new CompositeKey((Integer)this.getKeys().get("id"), (Integer)this.getKeys().get("otherid"));
}
}
class CompositeKey {
private Integer id;
private Integer otherId;
CompositeKey(Integer id, Integer otherId) {
this.id = id;
this.otherId = otherId;
}
public Integer getId() {
return id;
}
public Integer getOtherId() {
return otherId;
}
}
Here is the basic idea for a single key. The long id at the end is the key. If you have multiple sequences, I would recommend just using two separate statements to get each generated key.
JdbcTemplate template = getJdbcTemplate();
KeyHolder keyHolder = new GeneratedKeyHolder();
template.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(...);
return ps;
}
},
keyHolder);
long id = keyHolder.getKey().longValue();
What database server are you using? MySQL only allows one auto_increment field per table and I'd imagine this is often the case, but without knowing your setup it's hard to say. Assuming there is only one auto_generated field in your table, your INSERT would have had to be aware of the value going into the second PK field. Robert's code should work for retrieving the generated key value, and the cleanest solution would probably be to perform a SELECT after the fact using this generated key and the value which you had a hold of already.
I think what you need is GeneratedKeyHolder.getKeys(). Code would look like this example, except you will have to call
keyHolder.getKeys()
instead of
keyHolder.getKey()