How To Fix error? I am trying Update the Jtable row data and microsoft access database but it occurred issue.
It Update all rows from the access table instead selected row.
can anyone fix the error? or show me code for it?
**My code is**
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
String id, fname, lname;
connection = ConnectionDb.getConnection();
try{
String value1=txtFname.getText();
String value2=txtLname.getText();
PreparedStatement preparedStatement=connection.prepareStatement("Update Student SET FirstName = '"+value1+"' , LastName ='"+value2+"' where ID = +id");
preparedStatement.execute();
int i = jTable1.getSelectedRow();
if(i >= 0)
{
jTable1.setValueAt(txtFname.getText(), i, 0);
jTable1.setValueAt(txtLname.getText(), i, 1);
}else
{
JOptionPane.showMessageDialog(null, "Error");
}
connection.commit();
}catch(Exception e){
e.printStackTrace();
}
}
There are a few issues in your code:
First: You are not specifying an Id in the Where clause properly. So the update is updating everything.
// Your "Where" means basically "Where 1 = 1"
PreparedStatement preparedStatement=connection.prepareStatement("Update Student SET FirstName = '"+value1+"' , LastName ='"+value2+"' where ID = +id");
Second: It's better to use parameters instead of simply concatenating your variables. Here is how you could do it:
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
String id, fname, lname;
connection = ConnectionDb.getConnection();
try{
String value1=txtFname.getText();
String value2=txtLname.getText();
PreparedStatement preparedStatement = connection.prepareStatement("Update Student SET FirstName = ? , LastName = ? where ID = ?");
preparedStatement.setString(1, value1);
preparedStatement.setString(2, value2);
preparedStatement.setString(3, id);
preparedStatement.execute();
// Code continues..
....
Third: Where is your ID value? You created the variable in the second line but you didn't set any value there. You need to retrieve the value and use it in order to update your Student data.
Related
I designed a jTable that will display data from a table in MySql DB.
The table name is studentrolls with STRollID (int) as primary key and StudentID (Varchar), BachID (year) as foreign keys.
So after typing the StudentID in a jTextField and clicking a jButton only data concerning the student should be displayed in the jTable.
It's working actually but am having two problems, instead of displaying the Year on the year column it's displaying a date for example it should display 2020 but it displaying 2020-01-01.
The main problem is that when I enter another StudentID, it is adding the new results to the old one, so when I enter for the first time a StudentID I get good results and then when I enter another StudentID and click the button I get in the table the new results mixed with the first student's one, etc...
Is there any way to solve this and clear the table before inserting new results?
Here is my code :
private void rSButtonIconDsearchstidActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sqlqueryPastYHi = "SELECT * FROM studentrolls WHERE StudentID = ? ORDER BY BachID";
PreparedStatement preparedStatement = con.prepareStatement(sqlqueryPastYHi);
PreparedStatement pst=con.prepareStatement(sqlqueryPastYHi);
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1, jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent = String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace = String.valueOf(resultSet.getInt("PlaceFinale"));
String appication = resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction = resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass, totpercent, finalplace, appication, behavior, finalaction};
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.addRow(pastHistTableData);
}
}
else{
JOptionPane.showMessageDialog(this, "Veillez taper le matricule d'un eleve svp.");
}
}catch (Exception exception){
JOptionPane.showMessageDialog(this, "erreur des donnees: " + exception.getMessage());
}
}
is there any way to solve this and clear the table before inserting new results?
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while (...)
{
....
tblModel.addRow(...);
}
thanks #camickr i did changed the code as follow using your methode and it worked.
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1,
jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
DefaultTableModel tblModel =
(DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent =
String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace =
String.valueOf(resultSet.getInt("PlaceFinale"));
String appication =
resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction =
resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass,
totpercent, finalplace, appication, behavior,
finalaction};
tblModel.addRow(pastHistTableData);
}
I'm trying to fix this one for a while but can't find the or fix the code. The error triggered when I add a auto generated 'id' which is in method.
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
int row = jTable1.getSelectedRow();
String value = (jTable1.getModel().getValueAt(row, 0).toString());
String sql = "UPDATE category SET category_name = ? WHERE category_id = "+ value;
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, CategoryNameField.getText());
pstmt.executeUpdate();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
JOptionPane.showMessageDialog(null, "Record Updated Successfully ");
DisplayTable();
conn.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
You are correctly using a prepared statement, but you should be using a positional parameter in the WHERE clause instead of concatenation:
String sql = "UPDATE category SET category_name = ? WHERE category_id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, CategoryNameField.getText());
pstmt.setString(2, value);
pstmt.executeUpdate();
The exact cause of the error has to do with your WHERE clause comparing the category_id string column against an unescaped string literal, e.g.
WHERE category_id = some_value -- should be 'some_value'
SQL will interpret some_value as referring to a column, table, etc. name. By using a prepared statement (which you alreary are doing), you let the database handle the proper escaping of the values.
I have a bit of code here to get the next value of my sequence, but it is adding the total number of records onto the result each time.
I'm only learning about prepared Statements, I'm thinking this is something small, maybe rset.next() should be something else?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
Any help appreciated.
I think you don't need the call to pstmt.executeUpdate();
As stated in ResultSet doc, the function insertRow stores the row in the Dataset AND in the database.
The following code shows all that's necessary to add a new row:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
Why dont you iterate using while rather than if . something like this
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
Shouldn't you be doing this instead?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
As it is, it seems like you're passing a slightly bogus string into the SQL query, which is probably defaulting to the max index (not 100% positive on that). Then rs.next() is just incrementing that.
tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");
I have DDBB with a table users and I'm trying to get fields user_id and user_pass by searching for user_name.
So, when I run the following query:
SELECT `user_id`, `user_pass` FROM `users` WHERE `user_name` LIKE '%aName%';
It returns, ie aName = "John":
+---------+-----------+
| user_id | user_pass |
+---------+-----------+
| 5 | "1234" |
+---------+-----------+
Ok, then I want to perform this using a PreparedStatement, for that reason I have made this function:
private final String QUERY_GETUSERNAME2 =
"SELECT `user_id`, `user_fname`"
+ " FROM `users`"
+ " WHERE `user_fname` LIKE ?;";
private String[][] getUsersInv(String usrName){
ArrayList<String[]> alAux = new ArrayList();
String[][] ret = null;
try{
PreparedStatement st = _conn.prepareStatement(QUERY_GETUSERNAME2);
st.setString(1, "'%"+usrName+"%'");
ResultSet rs = st.executeQuery();
while(rs.next()){
String[] asAux = {String.valueOf(rs.getInt(1)), rs.getString(2)};
alAux.add(asAux);
}//while
}catch(SQLException e){
e.printStackTrace(System.out);
}finally{
if (!alAux.isEmpty()){
ret = new String[alAux.size()][alAux.get(0).length];
for (int i = 0; i < alAux.size(); i++)
ret[i] = alAux.get(i);
}//fi
}
return ret;
}
As you can see, the function returns a String[][], so I check in a previous function if returns is or not null:
public void insertUsersInvTableModel(JTable table, String user){
DefaultTableModel model = (DefaultTableModel) table.getModel();
String[][] row = getUsersInv(user);
if (row != null)
model.addRow(row);
}
And this function is call from the listener for a JButton:
private void addUserActionPerformed(java.awt.event.ActionEvent evt) {
if (comboUsers.getSelectedIndex() != 0){
new Users(_conn).insertUsersInvTableModel(_target, String.valueOf(comboUsers.getSelectedItem()));
_target.validate();
_target.repaint();
setVisible(false);
}
}
As you can imagine, there's a JDialog with a JComboBox with all the users listed down.
As table users is AUTO_INCREMENT, the user_id has some gaps (or maybe it will have), and the only way to build the JComboBox was without relate user_id to JComboBox index.
But, the problem is that whenever I pick an item from the JComboBox, and I run the process to get the user_id and user_pass based on the item selected (nor the index), the ResultSet is always NULL.
Any idea?
Thanks.
replace
st.setString(1, "'%"+usrName+"%'");
with
st.setString(1, "%"+usrName+"%");
The single quotes are automatically added by the PreparedStatement. With the Quotes the query will look for the String '%usrname%' instead of %usrname%
try
st.setString(1, "%"+usrName+"%");
instead of
st.setString(1, "'%"+usrName+"%'");
SOLUTION
As Marco Forberg pointed, quotes used for envolve the string parameter (') are not compulsory. Removing them fix the issue.