Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

public class Main {
    public static void main(String args[]) throws Exception {
        String URL = "jdbc:microsoft:sqlserver://yourServer:1433;databasename=pubs";
        String userName = "yourUser";
        String password = "yourPassword";

        Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
        Connection con = DriverManager.getConnection(URL, userName, password);
        CallableStatement callstmt = con
                .prepareCall("INSERT INTO myIdentTable (col2) VALUES (?);SELECT @@IDENTITY");
        callstmt.setString(1, "testInputBatch");
        callstmt.execute();

        int iUpdCount = callstmt.getUpdateCount();
        boolean bMoreResults = true;
        ResultSet rs = null;
        int myIdentVal = -1; // to store the @@IDENTITY

        while (bMoreResults || iUpdCount != -1) {
            rs = callstmt.getResultSet();
            if (rs != null) {
                rs.next();
                myIdentVal = rs.getInt(1);
            }
            bMoreResults = callstmt.getMoreResults();
            iUpdCount = callstmt.getUpdateCount();
        }
        callstmt.close();
        con.close();
    }
}