Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main {
    public static void main(String[] args) throws Exception {
        Connection con = DriverManager.getConnection("jdbc:mysql://192.168.1.3/zzzTest?" + //
                "useUnicode=yes&characterEncoding=UTF-8" + //
                "&user=root&password=whatever");
        String newName = "G";
        String newEmail = "g@example.com";
        String newMobile = "444-555-2222";
        String sql = "SELECT " + //
                "id, " + //
                "name, " + //
                "email, " + //
                "mobile " + //
                "FROM registerSmsUsers " + //
                "WHERE mobile = ? " + //
                "FOR UPDATE";
        PreparedStatement pst = con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
        pst.setString(1, newMobile);
        ResultSet rs = pst.executeQuery();
        if (rs.next()) {
            rs.moveToCurrentRow();
            rs.updateString("name", newName);
            rs.updateString("email", newEmail);
            rs.updateRow();
            System.out.println("Existing row updated.");
        } else {
            rs.moveToInsertRow();
            rs.updateString("name", newName);
            rs.updateString("email", newEmail);
            rs.updateString("mobile", newMobile);
            rs.insertRow();
            System.out.println("New row inserted.");
        }
    }
}