user962206
user962206

Reputation: 16117

JDBC MySQL Editing/Updating a current Entry in the Database

How can I edit a certain data entry in MySQL? for example I have table about a personal information, but I only want to edit the First Name table, can i just do it like this?

"Update Personal_Info
set first_name='"+getFirstName()+"' ,last_name = ?
where emp_id = 2011-01015" 

Where the question mark in the last name will retain it's value.I am using this kind of approach, because I do not want to hard code everything. you see in my UI , I'll use a form where the user will choose if he want's to update only the first name and last name. I came up with this idea since it would be easier for me. but suggestions are welcome.

Upvotes: 1

Views: 4921

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94645

Include only those columns whose value you want to update. Suppose if you want to update first_name then statement will be:

String sql="Update Personal_Info set first_name=? where emp_id=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,getFirstName()); // set parameter value for first_name
ps.setString(2,"2011-01015");   //     parameter value for emp_id    
ps.executeUpdate();
ps.close();
conn.close();

EDIT:

String sql="Update Personal_Info set first_name=? where emp_id='2011-01015'";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,getFirstName()); // set parameter value for first_name
ps.executeUpdate();
ps.close();
conn.close();

Upvotes: 3

Artem
Artem

Reputation: 4397

Yes, you can do this way. But you should consider using PreparedStatements to omit possible SQL injections in your app.

Upvotes: 0

Related Questions