Share on Google+Share on Google+

JDBC Update Statement Example

Advertisement
In this tutorial you will know how to update the record of a table using JDBC update statement

JDBC Update Statement Example

JDBC update statement is used to update the records of a table using java application program. The Statement object returns an int value that indicates how many rows updated.

At first create table named student in MySql database and inset values into it as.

CREATE TABLE student (
RollNo int(9)  PRIMARY KEY NOT NULL,
Name tinytext NOT NULL,
Course varchar(25) NOT NULL,
Address text );


JDBCUpdateExample.java

package oseindia.net;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUpdateExample {
	public static void main(String[] args) throws SQLException {
		Connection con = null; // connection reference variable for getting
		// connection
		Statement stmt = null; // Statement reference variable for query
		// Execution
		String conUrl = "jdbc:mysql://localhost:3306/";
		String driverName = "com.mysql.jdbc.Driver";
		String databaseName = "student";
		String usrName = "root";
		String usrPass = "root";
		try {
			// Loading Driver
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			System.out.println(e.toString());
		}
		try {
			// Getting Connection
			con = DriverManager.getConnection(conUrl + databaseName, usrName,
					usrPass);
			// Creating Statement for query execution
			stmt = con.createStatement();
			// creating Query String
			String query = "UPDATE student SET Name='John', Address='New York', Course='M.Tech' WHERE RollNo=1";
			// Updating Table
			int rows = stmt.executeUpdate(query);
			System.out.println(rows + " Rows Updated Successfully....");
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			// Closing Connection
			con.close();
			stmt.close();
		}
	}
}
When you run this application it will display message as shown below:

1 Rows Updated Successfully....

Download this example code

Advertisements

Advertisement

Posted on: October 13, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.