This code:
private void btnDeleteRecordActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
rs.deleteRow();
stmt.close();
rs.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM Workers";
rs = stmt.executeQuery(sql);
rs.next();
int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first = rs.getString("First_Name");
String last = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
textID.setText(id);
textFirstName.setText(first);
textLastName.setText(last);
textJobTitle.setText(job);
} catch (SQLException err) {
// System.out.println(err.getMessage());
JOptionPane.showMessageDialog(Workers.this, err.getMessage());
}
}
AfteI delete one row from database the program freeze. I want to that program will be able to work after a delete button te next and prevrious button will be work.
I used thie: http://www.homeandlearn.co.uk/java/delete_a_record_from_a_database.html
Firstly:
Rather define you Statement and ResultSet within the method you are doing the work, this is better use of scope and safer especially when working with multi-threaded code...
Secondly:
When querying for "Workers", map each row into a POJO and put all POJO's in a collection, then have your app work with the collection instead of the ResultSet.
Thirdly:
When doing an update/delete, create an update/delete statement and use the entries (you are trying to modify's) id (or some other type of unique reference) to the statement.
Looks like your thread is dying from a NullPointerException. First thing you should do would be to find out where the bug is that is causing the NullPointerException and fix it.
Related
I am facing a problem with retrieving a column from database
This is my code
public String ShowtimeQur(int MovieID)
{
rs3 = null;
String RoomID=null;
String ShowTime = null;
try
{
String qu ="Select Room_ID from Movie_Shows_in where Movie_ID="+MovieID;
//getRoomQur.setInt(1, MovieID);
rs3=getRoomQur.executeQuery(qu);
RoomID=rs3.getString("Room_ID");
getShowtimequr.setString(1, RoomID);
rs4=getShowtimequr.executeQuery();
ShowTime=rs4.getString("Show_Times");
}
catch (SQLException e)
{
e.printStackTrace();
}
return ShowTime;
}
I keep get this type of error
java.sql.SQLException: Invalid operation at current cursor position.
Use PreparedStatement.
PreparedStatement statement = con.prepareStatement("Select Room_ID from Movie_Shows_in where Movie_ID=?");
statement.setInt(1, MovieID);
ResultSet res = statement.executeQuery()
...
rest of your code
Never, never, never use string concatenation to build queries, as you put yourself at risk of SQL Injection
Like the answer before, you shoud declare a "ResulSet result" variable, and after the execute of the query, you should call "result.next()" method to point the cursor on the first row (initially is pointed to row 0 which does not exist) and then call a retrive data mehod like "result.getString(columnNumber)" by example.
Here's my code for the addStudent:
#FXML
private void addStudent(ActionEvent event) {
// sql query to insert data into students at ID, first name, last name, email and DOB
String sqlInsert = "INSERT INTO students(id,fname,lname,email,DOB) VALUES (?,?,?,?,?)";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sqlInsert);
// add the data in the right column
stmt.setString(1, this.id.getText());
stmt.setString(2, this.firstname.getText());
stmt.setString(3, this.lastname.getText());
stmt.setString(4, this.email.getText());
stmt.setString(5, this.dob.getEditor().getText());
stmt.execute();
conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
And here's my code for removeStudent:
#FXML
private void removeStudent(ActionEvent event) {
try {
// sql query to delete data from the database
String sqlRemove = "DELETE FROM students WHERE id = ?";
// open a connection to the database and use PreparedStatement to
// initialize the query.
Connection conn = dbConnection.getConnection();
PreparedStatement delete = conn.prepareStatement(sqlRemove);
// information needed to delete the row
delete.setString(1, selectStudent());
// execute and delete
delete.executeUpdate();
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// update table after deleting
loadStudentData(event);
}
The picture above is the view of my table. I hit LoadData and my table values show up. I want to be able to click on a row(student) and hit Delete Student to remove it.
Helper method for removeStudent:
private String selectStudent() {
String result = "";
try {
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
result = rs.getString(1);
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return result;
}
I'm pretty sure it has to do with when I "click" on a row, the id value for that isn't being held anywhere so when I hit "Delete" nothing is being given for it to Delete.
I don't know. Any advice would be awesome. :D
First edit: nothing is assigned to delete.setString(1, this.id.getText()). When I click on the row and hit delete, nothing is happening because there's nothing being assigned to id when I click on the row. The query string DOES work however when I physically give it an ID to delete. Also verified that the button does work; it prints out a lovely message for me with a good ol' System.out.println("expletive");
Second edit: Ok, so I updated the removeStudent code and now all I get is the string "null" returned. Nothing deletes. Nothing updates. Nothing is happening except I get "null" in the console.
Third edit: Getting closer! With the realization that the removeStudent isn't being given an ID to delete, I decided to create a private helper method that will do a SELECT query. Now, when I hit delete, it'll delete....but from the top, and not at where I want it selected. The code is above.
Fourth edit: Getting even closer! So, I figured out how to capture the row I click on within the table and I can delete......however, because of my sqlRemove command, I'm deleting by id so if I click on a row with index 3, then ONLY the row within the table that has an id of 3 will be deleted, nothing else. I gotta re-write how the sqlRemove command is worded.
I fixed it:
private String selectStudent() {
// initial value for result to return
String result = "";
// grab the index of the row selected on the table
int initial = studenttable.getSelectionModel().getSelectedIndex();
try {
// SELECT query to execute
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
// while there's a next row
while(rs.next()) {
// set temp to equal the id rs.next() is currently on
String temp = rs.getString("id");
// get the row id - 1 since we start at 0
int temp1 = rs.getRow() - 1;
// if temp1 is equal to the index we selected
if(temp1 == initial) {
// make it equal to result
result = temp;
}
}
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// return the row to delete
return result;
}
What's going on is in the comments. I finally figured out how to pass the value from a selected row and compare it to a row. Once I get the correct row to pass, I give it to the delete function to remove.
After a day in a half.............but I love it, so. Yeah.
It Takes Too Long For Me To Create And Send PreparedStatement's or ResultSet.
How Can I Get MaxID From SQL in Java Method?
Writed this but not working...
private static int getLastId()
{
int returned=0;
try
{
PreparedStatement stat;
ResultSet rs;
String sql="select max(id) from home";
stat=conn.prepareStatement(sql);
rs=stat.executeQuery();
while(rs.next())
{
returned = rs.getInt("id")+1;// just want a new id for new person
}
}
catch (Exception e)
{
System.out.println(""+e);
}
return returned;
}
I Tried To Use It Like This...
//reseting every thing and get lastId+1;
System.out.println("added");
field_name.setText("");
field_pass.setText("");
int temp= getLastId();
field_id.setText(""+temp);
But It Returns 0!
I Don't Have any SQL error.
Did I Use It Wrong?
or ?
Thanks For Help.
You have a few problems here, one of which is that in your current code you aren't actually accessing the max(id) which you put in the query. One way around this is to assign an alias:
PreparedStatement stat;
ResultSet rs;
String sql = "SELECT MAX(id) AS max_id FROM home";
stat = conn.prepareStatement(sql);
rs = stat.executeQuery();
if (rs.next()) {
returned = rs.getInt("max_id") + 1;
}
This fixes the syntax problem, but there is still the problem of whether this is the best way to get the next id. I would recommend that you switch to using an auto increment column, which MySQL will manage for you. Then, you don't need to worry about keeping track of the latest ID value. In fact, you don't even need to specify a value when inserting; the database will handle this for you.
I'm trying to execute a prepared statement in JDBC, and everytime I execute it I get the error message "Paramater not set".
I have tried repeatedly to check for unset parameters - but I only have the one. This leads me to believe it is another foolish error on my part.
If you could point this out to me, I would be very grateful
public book search(String key){
book temp = null;
try {
String stmt = "SELECT BookID, Title, Author, Media, Available FROM BOOK WHERE Title LIKE ?;";
connection = DatabaseConnection();
PreparedStatement preparedStmt = connection.prepareStatement(stmt);
System.out.println(key);
preparedStmt.setObject(1, key);//the name
statement = connection.prepareStatement(stmt); //Using Prepared Statements prepare the query
resultSet = statement.executeQuery(); //Execute the query
while (resultSet.next()) {
int bookID = resultSet.getInt("BookID");//Get the userName
String title = resultSet.getString("Title"); //Get the score
String author = resultSet.getString("Author"); //Get the score
String media = resultSet.getString("Media"); //Get the score
boolean available = resultSet.getBoolean("Available"); //Get the score
temp = new book(title,author,media,available,bookID);
}
connection.close(); //close connection
} catch (SQLException e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return temp;
}
You're calling prepareStatement twice, setting the parameter on the first one but then calling executeQuery on the second.
It's not clear where you're event declaring statement or resultSet, but you want:
PreparedStatement preparedStmt = connection.prepareStatement(stmt);
preparedStmt.setString(1, key);
ResultSet resultSet = preparedStmt.executeQuery();
Note that I've made resultSet a local variable - you really don't want it to be a field... there's also no reason for your temp variable as you can just return directly from the while loop. (I've changed the code to use setString instead of setObject, too...)
You should use try-with-resources statements to close both the statement and the result set automatically...)
i want to update a date in the database under some condition, so i tried this method that i call it in button action performed
public void DeleteDate (JTextField txt1, JTextField txt2)
{
try {
Class.forName("com.mysql.jdbc.Driver");
String m = "IMCDietitian";
String unicode= "?useUnicode=yes&characterEncoding=UTF-8";
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/"+m+""+unicode+"","root","");
System.out.println("connected");
String dept = jComboBox1.getSelectedItem().toString();
Statement st = conn.createStatement();
st.executeUpdate("UPDATE "+dept+" SET edate = '"+jTextField1.getText()+"' WHERE pname = '"+txt1.getText()+"' AND rno = '"+txt2.getText()+"' AND edate = '-'");
}
catch (Exception e) {
e.printStackTrace();
}
}
But it doesn't update any thing in the database. Can any one help me?
There could be these reasons for not seeing any updates:
Perhaps the where clause does not result in any rows being returned therefore no row is updated.
Perhaps autocommit is false. In this case you would need to call commit explicitly. As a note, you could also take a look at transactions.
An Exception but it seems that in this case there is none.
Also, use PreparedStatement - it is cleaner and gets compiled for reuse.