The example in this article describes the methods that the JDBC program updates records in the database. Share to everyone for your reference, specific as follows:
When you update a record in a database (MYSQL) using the JDBC program (Eclipse, MyEclipse), you can modify only one field or several fields of the record by adding the following annotated code (provided that you can get the record from the database before you modify) take the user table as an example
public class Userdaojdbcimpl implements Userdao {public void update (User u) {Connection conn = null;
PreparedStatement PS = null;
ResultSet rs = null;
try {conn = jdbcutils.getconnection (); String sql = "Update user set name =?, Birthday =?, Money =?"
where id=? ";
PS = conn.preparestatement (SQL);
First get the record user user = Getuserbyid (U.getid ());
Determine if the field needs to modify if (u.getname () = = null) {U.setname (User.getname ());
} if (u.getbirthday () = = null) {U.setbirthday (User.getbirthday ());
} if (U.getmoney () = = 0) {U.setmoney (User.getmoney ());
Ps.setstring (1, U.getname ());
Ps.setdate (2, New Java.sql.Date (U.getbirthday (). GetTime ()));
Ps.setdouble (3, U.getmoney ());
Ps.setint (4, U.getid ());
int i = Ps.executeupdate ();
SYSTEM.OUT.PRINTLN ("Update" + i + "record" in the user table successfully);
catch (SQLException e) {e.printstacktrace ();
Finally {Jdbcutils.free (RS, PS, conn);
The public User Getuserbyid (int id) {Connection conn = null; PreparedStatement PS =Null
ResultSet rs = null;
User user = null;
try {conn = jdbcutils.getconnection ();
String sql = "SELECT * from user where id =?";
PS = conn.preparestatement (SQL);
Ps.setint (1, id);
rs = Ps.executequery ();
if (Rs.next ()) {user = new user ();
User.setid (Rs.getint ("id"));
User.setname (rs.getstring ("name"));
User.setbirthday (rs.getdate ("Birthday"));
User.setmoney (rs.getdouble ("money"));
} catch (SQLException e) {e.printstacktrace ();
Finally {Jdbcutils.free (RS, PS, conn);
return to user;
}
}
Call:
public static void Main (string[] args) {
Userdao ud = new Userdaojdbcimpl ();
User user = new user ();
User.setid (9);
User.setname ("Teacher")//only modifies the name and birthday properties
Date d = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd");
D = Sdf.parse ("1999-9-14");
} catch (ParseException e) {
e.printstacktrace ();
}
User.setbirthday (d);
User.setmoney (1234); Do not modify the Money attribute
ud.update (user);
I hope this article will help you with Java programming.