Well the main problem here is, the detection of the duplicate entries in the Jtable, the Detection of duplicate entries will work when your enter the SAME/IDENTICAL data for the third time. It would not work in the second time and duplicate.
how can i add a unique constrain in my mysql? i dont know how to do it. Please let me have a specific instructions on how to execute it
2nd try (duplicate)
3rd try(the detection works)
database
JAVA NETBEANS
DATABASE: MYSQL
I think the problem would be the try-catch part which is the part that I dont understand. Thank You in Advance.
Heres my codes:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String first = firstname.getText();
String last = lastname.getText();
String gen = gender.getText();
String strand = cboStrand.getSelectedItem().toString();
String aged = age.getText();
String add = address.getText();
try{
String sql;
sql = "INSERT INTO idusjavanew"
+ "(fname,lname,sex,strand,age,address)"
+ "VALUES (?,?,?,?,?,?)";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/idusjavanew?zeroDateTimeBehavior=convertToNull","root","");
pst = con.prepareStatement(sql);
pst.setString(1, firstname.getText());
pst.setString(2, lastname.getText());
pst.setString(3, gender.getText());
pst.setString(4, cboStrand.getSelectedItem().toString());
pst.setString(5, age.getText());
pst.setString(6, address.getText());
String selectQuery;
selectQuery = "select * from idusjavanew where fname ='"+first+"' and lname='"+last+"'";
System.out.println(selectQuery);
rs = pst.executeQuery(selectQuery);
System.out.println(rs.next());
if (rs.next()==false){
pst.executeUpdate();
JOptionPane.showMessageDialog(null , "Information has been recorded!");
showTableData();
}
else{
JOptionPane.showMessageDialog(null,"Information already added!");
showTableData();
}
}
catch(HeadlessException | SQLException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
showTableData();
}
You are calling next() twice on your result set once in print statement and once in if, that is causing the issue.
So according to your current code if you already have an entry the 1st call to next() will point it to that entry and the second call will return false. That is why it detects duplicate on third row entry.
So just remove System.out.println(rs.next()); and your code should work as intended.
Related
image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}
EDITED I´ve changed the SQL code and it works, but I get the exception:
"cannot set a null tableModell
I´ve seen many very similar examples but not the one I need.
Therefore here we go:
It´s simple - In a InternalFrame I insert Code, ProjectName, Teamleiter, Description and click "Teilnehmer" to list all members of all projects from a table "tbl_teinehmer". Just the Lastname is shown.
So, I insert the correspondent data into the fields, list the projectmembers and select the members who will take part of this new project I´m creating.
In order to insert the data and the selected row from "teilnehmer" into a new Table:
private void buttonAnlegenActionPerformed(java.awt.event.ActionEvent evt) {
String data = tbl_teilnehmer.getValueAt(tbl_teilnehmer.getSelectedRow(), 0).toString();
String sql = "INSERT INTO TBL_PROJETO (PROJEKT_ID, PROJEKTNAME, TEAMLEITER, BESCHREIBUNG,**TEILNEHMER**)"; //now it works but I get the exception: cannot set a null TableModell.
+ " VALUES(?,?,?,?,?)";
menu = new HauptMenu();
try{
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, ct.getText());
pst.setString(2, nt.getText());
pst.setString(3, st.getText());
pst.setString(4, beschreibungText.getText());
pst.setString(5, data);
pst.execute();
menu.listaProjetos();
JOptionPane.showMessageDialog(null, "Projekt added to Database");
}
catch(Exception e){
System.out.println(e);
}
try{
conn.close();
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
ct.setText("");
nt.setText("");
st.setText("");
}
This is the error:
java.sql.SQLException: Parameter index out of range (5 > number of parameters, which is 4).
Maybe the problem is by PreparedStatemend declaration.
I´ve set
pst.setString(5, data);
as it would recognize the selected row from the variable data but I guess it´s wrong.
do it as follows
pst.setString(0, ct.getText());
pst.setString(1, nt.getText());
pst.setString(2, st.getText());
pst.setString(3, beschreibungText.getText());
pst.setString(4, data);
Thank you for helping me!
I solved the problem first by changing the SQL declaration:
First at I´ve placed '"+data+"', which is an placeholder(If I´m not mistaken) but I wanted to set the selected row into the respective column in DB.
Therefore I´ve changed it to the columnname: TEILNEHMER and set another questionmark '?' as VALUE.
It worked but I still got the error>> cannot set a null TableModel
and under this error >> Unsupported collation 'Latin7' or smth like that.
So I´ve set the Collation of my table from Lati7 to TableDefault and now it works entirely.
THANK YOU ALL AGAIN FOR HELPING ME!
There is no placeholder for 5th parameter in your sql query:
String sql = "INSERT INTO TBL_PROJETO (PROJEKT_ID, PROJEKTNAME, TEAMLEITER, BESCHREIBUNG,'"+data+"')"
+ " VALUES(?,?,?,?,?)";
I'm creating a program where I should save data on database. I have two frames but only using one table in one database and on the first frame I already saved data on row 1-6. Now on the second frame I want to add data on row 7-12 only. How can I do this? Or should I make another table instead?
I'm newbie to Java, so help would be great.
Here's my code for the save:
JOptionPane.showMessageDialog(this, "Save this input?", "Confirm", JOptionPane.QUESTION_MESSAGE);
strCountry = txtCountry.getText();
strMembers = txtareaMembers.getText();
strSong = txtSong.getText();
strAlbum = txtAlbum.getText();
Concert = (String) cmbConcerts.getSelectedItem();
Biblio = (String) cmbBiblio.getSelectedItem();
btnSubFirst.setEnabled(false);
btnSubPrev.setEnabled(false);
btnSubNext.setEnabled(true);
btnSubLast.setEnabled(true);
btnSubEdit.setEnabled(false);
btnSubSave.setEnabled(false);
btnSubCancel.setEnabled(true);
txtCountry.setEditable(false);
txtSong.setEditable(false);
txtAlbum.setEditable(false);
SaveData();
public void SaveData() {
try {
String strQuery = "INSERT INTO tblband(bandname,label,genre,year,member,album,country,members,song,recent,concert,biblio)" + "VALUES" + "(?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/banddb", "root", "");
st = con.prepareStatement(strQuery);
st.setString(1, strBand);
st.setString(2, strRecord);
st.setString(3, Genre);
st.setString(4, Year);
st.setString(5, Member);
st.setString(6, Album);
st.setString(7, strCountry);
st.setString(8, strSong);
st.setString(9, strAlbum);
st.setString(10, Concert);
st.setString(11, Biblio);
st.setString(12, strMembers);
st.executeUpdate();
con.close();
JOptionPane.showMessageDialog(null, "Data is successfully inserted into database.");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error in submitting data." + e);
}
}
You could use an update query:
The UPDATE statement is used to update existing records in a table.
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
A working example of this can be found: here.
Notice the WHERE clause in the SQL UPDATE statement!
The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
I have a two database table, on a single button click in my program , I want to delete all the two table's data. But there's always one datum left on the table.. Here is my code:
public void mouseClicked(MouseEvent arg0) {
int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete the log? ", "Log", JOptionPane.YES_NO_OPTION );
if (confirm == JOptionPane.YES_OPTION){
try{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:RIM");
Statement st1 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
Statement st2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql1 = "select * from userLogIn";
ResultSet rs1 = st1.executeQuery(sql1);
String sql2 = "select * from userViewed";
ResultSet rs2 = st2.executeQuery(sql2);
while(rs1.next()){
rs1.deleteRow();
rs1.first();
}
while(rs2.next()){
rs2.deleteRow();
rs2.first();
}
editorPane.setText("");
}catch(Exception e){e.printStackTrace();}
When there is only one element left, your call to first() sets the cursor to that element, but then the next() call in the while condition will return false, causing the exit from the loop and thus the deleteRow won't be executed.
Use rs.beforeFirst()`.
Note that your code has lots of issues, so get this answers as "for educational purposes" only.
Why are you iterating over a select record set at all? It's incredibly inefficient.
If you want to delete all data from those tables, you can simply execute the statements:
delete from userLogin;
delete from userViewed;
(or use truncate).
I have a MySQL table with entries already in it and I have it connected to my Java program so it displays the table values whenever the program is run. I'm basically trying to implement a search field where the user can type any attribute's value and all the entries that match that value will be loaded into the table. Then the user will be able to select the right entry that matches and they can edit, or update that entry's information. This would be useful for me particularly when you have entries that have the same value, for instance first name, last name, or zip code.
try {
String sql = "SELECT * FROM donors WHERE donor_id = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
try {
String sql = "SELECT * FROM donors WHERE first_name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
The search field only searches for the second query, but not the first, so I can type a name and the matching names will load into the table, but when I try to input an id number, nothing happens. I'm fairly new to this, but I think it has something to do with my resultset object? Not exactly sure though. Any help would be great.
What happens here is that the second result overwrites the first. I think the easiest solution is to use or in the where clause, like this:
String sql = "SELECT * FROM donors WHERE (donor_id = ?) or (first_name = ?)";
ps.setString(1, txtSearch1.getText());
// but of course there are 2 ?'s now, we have to give the value to the second one
// as well
ps.setString(2, txtSearch1.getText());
Due to the way placeholders work in JDBC you'll have to provide a value for each ?.