The Java code for updating a record in a MYSQL table using JDBC is given below:
import java.sql.*;
public class UpdateData {
static final String DB_URL = "jdbc:mysql://localhost/sampledb";
static final String USER = "root";
static final String PASS = "123456";
static final String QUERY = "UPDATE students SET mobile=7788665544 where id=5";
public static void main(String[] args) {
// Open a connection
try
{
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
int rs = stmt.executeUpdate(QUERY);
System.out.println("No. of rows updated = " + rs);
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Output for the above program is given below:
No. of rows updated = 1
In the above program we are updating the mobile number of a student with id 5 to a new number.
Note: The above compiles successfully only when we add the JAR file to the CLASSPATH environment variable as shown below:
The data in the table after the above update is given below:
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply