user3268379
user3268379

Reputation: 141

Java sql update row in database

I have got adding a member to the database working. I am trying to work out how to update a row in the table using the same system of passing in the values just not adding a new row, just altering the row using the passed in username.

Here is my method for inserting a new member:

 public static void insertMember(String username,String firstName)
{

    try 
     {  
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, username, password);

        PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES (?,?)");
        st.setString(1, username);
        st.setString(2, firstName);
        st.executeUpdate();    
     } 

     catch (SQLException e) 
     {
        System.out.println("SQL Exception: "+ e.toString());
     } 

     catch (ClassNotFoundException cE) 
     {
        System.out.println("Class Not Found Exception: "+ cE.toString());
     }


}

Upvotes: 0

Views: 1746

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347334

You need to use an UPDATE command instead of INSERT command.

Take a look at SQL UPDATE statement.

You will need to provide some means by which you can identify the row which needs to be updated, but this is dependent upon the structure of your table

Upvotes: 3

Dark Knight
Dark Knight

Reputation: 8357

Need to change SQL command instead of INSERT , uses UPDATE. Below code will update username for matching firstname provided in where clause.

          PreparedStatement st = connection.prepareStatement("UPDATE Members set username=? where firstName=?)");
         st.setString(1, username);
         st.setString(2, firstName);
         int updateStatus=st.executeUpdate();  

Upvotes: 0

SpringLearner
SpringLearner

Reputation: 13854

I have got adding a member to the database working. I am trying to work out how to update a row in the table using the same system of passing in the values just not adding a new row, just altering the row using the passed in username.

you need Update command

like

UPDATE Members set username='somename',firstname='firstname' where condition

Upvotes: 2

Related Questions