How to Modify Contents Using JDBC in Java


Here we will learn how to update a record in a table via JDBC statement.To load the driver, we will use mysql-connector-java-5.1.47 in the lib folder.

Source Code

1)

package com.beginner.examples;

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

public class DBConnection {
	// Declares a connection object
	private Connection dbConnection = null;
	
	// Declare the load-driven string
	private String driveString = "com.mysql.jdbc.Driver";
	
	// The Url string for the database
	private String urlMysqlString =
			"jdbc:mysql://localhost:3306/Test?useSSL=false";

	public DBConnection() throws Exception { 
		// The load driver
		Class.forName(this.driveString);
		// Get a database connection object and assign it to the dbconnection
		dbConnection = 
				DriverManager.getConnection(urlMysqlString, "root","root");
	}

	public Connection getDbConnection() {
		return this.dbConnection;
	}
	public void close() throws SQLException
	{
		dbConnection.close();
	}

}

2)

package com.beginner.examples;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCConnectionUpdateData {

	public static void main(String[] args) {

		try {
			DBConnection dbConnection = new DBConnection();

			// Gets the connection database object
			Connection connection = dbConnection.getDbConnection();

			// Create the execute Sql statement object
			Statement statement = connection.createStatement();
			
			// View the data in the table
			ResultSet set = statement.executeQuery("select * from student");
			printResultSet(set);

			// Execute an Sql statement to update the data
			statement
					.execute("update student set major="computer" where id=0021");

			// Look at the data in the table again
			ResultSet set1 = statement.executeQuery("select * from student");
			System.out.println("**********************************");
			printResultSet(set1);

			dbConnection.close();
		} catch (Exception e) {
			System.out.println(e);
		}

	}

	// Method to print the data in a ResultSet
	public static void printResultSet(ResultSet r) {
		try {

			while (r.next()) {
				String idString = r.getString(1);
				String namesString = r.getString(2);
				String major = r.getString(3);

				System.out.println("id-------" + idString + "nname------"
						+ namesString + "nmajor------" + major + ""
						+ "n-----------------------");

			}

		} catch (Exception e) {
			System.out.println(e);
		}

	}

}

Output:

id-------0021
name------Tom
major------Electronic
-----------------------
id-------0022
name------John
major------computer
-----------------------
**********************************
id-------0021
name------Tom
major------computer
-----------------------
id-------0022
name------John
major------computer
-----------------------

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments