Jdbc update example in java

UPDATE records in a table with JDBC

The JDBC classes and interfaces are available in java.sql and javax.sql packages.

Steps to update records in a table with UPDATE SQL statement using JDBC —

Class.forName("oracle.jdbc.driver.OracleDriver");

In the upcoming example, we are going to create a table within the Oracle database using its JDBC driver.

Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott", "tiger");
  • 1521 is the general port number to connect to the database.
  • XE stands for Oracle Express Edition Database.
  • scott is our username to connect to the Oracle database and tiger is the password.
Statement stmt = con.createStatement();

Creating a Statement object to using createStatement() method of Connection interface.

int count = stmt.executeUpdate(query);

count gives us the total number of rows updated in a database table due to the execution of a SQL query using executeUpdate() method, where query is a String object which specifies the SQL query to execute.

con is a Connection reference used to close the connection with the database after the updation is over.

Updating data in database table using JDBC

 import java.sql.*; class A < public static void main(String. ar) < try < //First SQL UPDATE Query to update record. String query1 = "Update MyTable2 Set FirstName='Thomas' Where FirstName = 'Tom'"; //Second SQL UPDATE Query to update record. String query2 = "Update MyTable2 Set FirstName='Bradly' where age = '53'"; //Third SQL SELECT Query to retrieve updated records. String query3 = "SELECT * FROM MyTable2"; Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","System", "Promila21"); Statement stmt = con.createStatement(); //Executing first SQL UPDATE query using executeUpdate() method of Statement object. int count = stmt.executeUpdate(query1); System.out.println("Number of rows updated by executing query1 = " + count); //Executing second SQL UPDATE query using executeUpdate() method of Statement object. count = stmt.executeUpdate(query2); System.out.println("Number of rows updated by executing query2 = " + count); //Executing SQL SELECT query using executeQuery() method of Statement object. ResultSet rs = stmt.executeQuery(query3); System.out.println("Result of executing query3 to display updated records"); System.out.println("ID " + "\t" + "FirstName" + "\t" + "LastName" + "\t" + "Age"); //looping through the number of row/rows retrieved after executing SELECT query3 while(rs.next()) < System.out.print(rs.getString("ID") + "\t"); System.out.print(rs.getString("FirstName") + "\t" + "\t"); System.out.print(rs.getString("LastName")+ "\t" + "\t"); System.out.println(rs.getString("Age") + "\t"); >> catch(SQLException e) < System.out.println(e); >>//main() method ends >//class definitin ends 

Output

Number of rows updated by executing query1 = 1 Number of rows updated by executing query2 = 1 Result of executing query3 to display updated records ID FirstName LastName Age 1 Thomas Hanks 61 2 Johnny Depp 54 3 Bradly Pitt 53

    In the output, you may see the updated records in table MyTable, where FirstName Tom is changed to Thomas and Brad is changed to Bradley.

ID FirstName LastName Age
1 Thomas Hanks 61
2 Johnny Depp 54
3 Bradley Pitt 53

Table — MyTable

Источник

Java Guides

In this article, we will discuss how to update a record in a database table via JDBC statement. JDBC Statement interface provides Statement.executeUpdate() method from which we can update a record in a database table as:

Statement statement = connection.createStatement(); // Step 3: Execute the query or update query int result = statement.executeUpdate(UPDATE_USERS_SQL); System.out.println("Number of records affected :: " + result);

Technologies used

Steps to Process Update SQL statement with JDBC

  1. Establishing a connection
  2. Create a statement
  3. Execute the query
  4. Using try-with-resources Statements to Automatically Close JDBC Resources

From JDBC 4.0, we don’t need to include ‘Class.forName()’ in our code, to load JDBC driver. When the method ‘getConnection’ is called, the ‘DriverManager’ will automatically load the suitable driver among the JDBC drivers that were loaded at initialization and those loaded explicitly using the same class loader as the current application.

Connection conn = DriverManager.getConnection(Urldatabase,Username,Password);

Any JDBC 4.0 drivers that are found in your classpath are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)

JDBC Statement Update Record Example

package com.javaguides.jdbc.statement.examples; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * Update Statement JDBC Example * @author Ramesh Fadatare * */ public class UpdateStatementExample < private static final String UPDATE_USERS_SQL = "update users set name = \"Ram\" where style="box-sizing: border-box;">"; public static void main(String[] argv) throws SQLException < UpdateStatementExample updateStatementExample = new UpdateStatementExample(); updateStatementExample.updateRecord(); > public void updateRecord() throws SQLException < System.out.println(UPDATE_USERS_SQL); // Step 1: Establishing a Connection try (Connection connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root"); // Step 2:Create a statement using connection object Statement statement = connection.createStatement();) < // Step 3: Execute the query or update query int result = statement.executeUpdate(UPDATE_USERS_SQL); System.out.println("Number of records affected :: " + result); > catch (SQLException e) < // print SQL exception information printSQLException(e); > // Step 4: try-with-resource statement will auto close the connection. > public static void printSQLException(SQLException ex) < for (Throwable e: ex) < if (e instanceof SQLException) < e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) < System.out.println("Cause: " + t); t = t.getCause(); > > > > >
update users set name = "Ram" where of records affected :: 1 

Note that Statement.executeUpdate() method returns either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing.

int result = statement.executeUpdate(UPDATE_USERS_SQL); System.out.println("Number of records affected :: " + result);

Источник

Java Guides

In the previous tutorial, we have seen how to insert records into a table in a PostgreSQL database using Java. In this tutorial, you will learn how to update data in a PostgreSQL database using the JDBC API.

  • Create a database connection.
  • Create a PreparedStatement object.
  • Execute the UPDATE statement by calling the executeUpdate() method of the PreparedStatement object.
  • Close the database connection.

Technologies used

Download PostgreSQL JDBC Driver

To connect to the PostgreSQL database server from a Java program, you need to have a PostgreSQL JDBC driver. You can download the latest version of the driver on the postgresql.org website via the download page.

 https://mvnrepository.com/artifact/org.postgresql/postgresql --> dependency> groupId>org.postgresqlgroupId> artifactId>postgresqlartifactId> version>42.2.9version> dependency>
// https://mvnrepository.com/artifact/org.postgresql/postgresql compile group: 'org.postgresql', name: 'postgresql', version: '42.2.9'

PostgreSQL Database Setup

JDBC PostgreSQL Update Example

package net.javaguides.postgresql.tutorial; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Update PreparedStatement JDBC Example * @author Ramesh Fadatare * */ public class UpdateRecordExample < private final String url = "jdbc:postgresql://localhost/mydb"; private final String user = "postgres"; private final String password = "root"; private static final String UPDATE_USERS_SQL = "update users set name = ? where style="box-sizing: border-box;">"; public static void main(String[] argv) throws SQLException < UpdateRecordExample updateStatementExample = new UpdateRecordExample(); updateStatementExample.updateRecord(); > public void updateRecord() throws SQLException < System.out.println(UPDATE_USERS_SQL); // Step 1: Establishing a Connection try (Connection connection = DriverManager.getConnection(url, user, password); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) < preparedStatement.setString(1, "Ram"); preparedStatement.setInt(2, 1); // Step 3: Execute the query or update query preparedStatement.executeUpdate(); > catch (SQLException e) < // print SQL exception information printSQLException(e); > // Step 4: try-with-resource statement will auto close the connection. > public static void printSQLException(SQLException ex) < for (Throwable e: ex) < if (e instanceof SQLException) < e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) < System.out.println("Cause: " + t); t = t.getCause(); > > > > >

Источник

Читайте также:  Python get timezone offset
Оцените статью