Search in sources :

Example 1 with SQLServerDataSource

use of com.microsoft.sqlserver.jdbc.SQLServerDataSource in project mssql-jdbc by Microsoft.

the class executeStoredProcedure method main.

public static void main(String[] args) {
    // Declare the JDBC objects.
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    String serverName = null;
    String portNumber = null;
    String databaseName = null;
    String username = null;
    String password = null;
    try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
        System.out.print("Enter server name: ");
        serverName = br.readLine();
        System.out.print("Enter port number: ");
        portNumber = br.readLine();
        System.out.print("Enter database name: ");
        databaseName = br.readLine();
        System.out.print("Enter username: ");
        username = br.readLine();
        System.out.print("Enter password: ");
        password = br.readLine();
        // Establish the connection.
        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName(serverName);
        ds.setPortNumber(Integer.parseInt(portNumber));
        ds.setDatabaseName(databaseName);
        ds.setUser(username);
        ds.setPassword(password);
        con = ds.getConnection();
        createTable(con);
        createStoredProcedure(con);
        // Create test data as an example.
        StringBuffer buffer = new StringBuffer(4000);
        for (int i = 0; i < 4000; i++) buffer.append((char) ('A'));
        PreparedStatement pstmt = con.prepareStatement("UPDATE Document_JDBC_Sample " + "SET DocumentSummary = ? WHERE (DocumentID = 1)");
        pstmt.setString(1, buffer.toString());
        pstmt.executeUpdate();
        pstmt.close();
        // Query test data by using a stored procedure.
        CallableStatement cstmt = con.prepareCall("{call GetLargeDataValue(?, ?, ?, ?)}");
        cstmt.setInt(1, 1);
        cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
        cstmt.registerOutParameter(3, java.sql.Types.CHAR);
        cstmt.registerOutParameter(4, java.sql.Types.LONGVARCHAR);
        // Display the response buffering mode.
        SQLServerCallableStatement SQLcstmt = (SQLServerCallableStatement) cstmt;
        System.out.println("Response buffering mode is: " + SQLcstmt.getResponseBuffering());
        SQLcstmt.execute();
        System.out.println("DocumentID: " + cstmt.getInt(2));
        System.out.println("Document_Title: " + cstmt.getString(3));
        Reader reader = SQLcstmt.getCharacterStream(4);
        // If your application needs to re-read any portion of the value,
        // it must call the mark method on the InputStream or Reader to
        // start buffering data that is to be re-read after a subsequent
        // call to the reset method.
        reader.mark(4000);
        // Read the first half of data.
        char[] output1 = new char[2000];
        reader.read(output1);
        String stringOutput1 = new String(output1);
        // Reset the stream.
        reader.reset();
        // Read all the data.
        char[] output2 = new char[4000];
        reader.read(output2);
        String stringOutput2 = new String(output2);
        System.out.println("Document_Summary in half: " + stringOutput1);
        System.out.println("Document_Summary: " + stringOutput2);
        // Close the stream.
        reader.close();
    }// Handle any errors that may have occurred.
     catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (rs != null)
            try {
                rs.close();
            } catch (Exception e) {
            }
        if (stmt != null)
            try {
                stmt.close();
            } catch (Exception e) {
            }
        if (con != null)
            try {
                con.close();
            } catch (Exception e) {
            }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) SQLServerCallableStatement(com.microsoft.sqlserver.jdbc.SQLServerCallableStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) PreparedStatement(java.sql.PreparedStatement) SQLServerDataSource(com.microsoft.sqlserver.jdbc.SQLServerDataSource) Connection(java.sql.Connection) BufferedReader(java.io.BufferedReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) SQLServerCallableStatement(com.microsoft.sqlserver.jdbc.SQLServerCallableStatement) SQLServerCallableStatement(com.microsoft.sqlserver.jdbc.SQLServerCallableStatement) CallableStatement(java.sql.CallableStatement) ResultSet(java.sql.ResultSet) BufferedReader(java.io.BufferedReader)

Example 2 with SQLServerDataSource

use of com.microsoft.sqlserver.jdbc.SQLServerDataSource in project mssql-jdbc by Microsoft.

the class ConnectionDriverTest method testIncorrectPassword.

@Test
public void testIncorrectPassword() throws SQLException {
    long timerStart = 0;
    long timerEnd = 0;
    Connection con = null;
    final long milsecs = threshHoldForNoRetryInMilliseconds;
    try {
        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setURL(connectionString);
        ds.setLoginTimeout(loginTimeOutInSeconds);
        ds.setPassword(RandomUtil.getIdentifier("Password"));
        timerStart = System.currentTimeMillis();
        con = ds.getConnection();
    } catch (Exception e) {
        assertTrue(e.getMessage().contains("Login failed"));
        timerEnd = System.currentTimeMillis();
    }
    long timeDiff = timerEnd - timerStart;
    assertTrue(con == null, "Should not have connected.");
    assertTrue(timeDiff <= milsecs, "Exited in more than " + (milsecs / 1000) + " seconds.");
}
Also used : SQLServerDataSource(com.microsoft.sqlserver.jdbc.SQLServerDataSource) Connection(java.sql.Connection) PooledConnection(javax.sql.PooledConnection) SQLServerConnection(com.microsoft.sqlserver.jdbc.SQLServerConnection) ISQLServerConnection(com.microsoft.sqlserver.jdbc.ISQLServerConnection) DBConnection(com.microsoft.sqlserver.testframework.DBConnection) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLException(java.sql.SQLException) AbstractTest(com.microsoft.sqlserver.testframework.AbstractTest) Test(org.junit.jupiter.api.Test)

Example 3 with SQLServerDataSource

use of com.microsoft.sqlserver.jdbc.SQLServerDataSource in project mssql-jdbc by Microsoft.

the class ConnectionDriverTest method testThreadInterruptedStatus.

/**
 * Test thread's interrupt status is not cleared.
 *
 * @throws InterruptedException
 */
@Test
@Tag("slow")
public void testThreadInterruptedStatus() throws InterruptedException {
    Runnable runnable = new Runnable() {

        public void run() {
            SQLServerDataSource ds = new SQLServerDataSource();
            ds.setURL(connectionString);
            ds.setServerName("invalidServerName" + UUID.randomUUID());
            ds.setLoginTimeout(5);
            try {
                ds.getConnection();
            } catch (SQLException e) {
                isInterrupted = Thread.currentThread().isInterrupted();
            }
        }
    };
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future<?> future = executor.submit(runnable);
    Thread.sleep(1000);
    // interrupt the thread in the Runnable
    future.cancel(true);
    Thread.sleep(8000);
    executor.shutdownNow();
    assertTrue(isInterrupted, "Thread's interrupt status is not set.");
}
Also used : SQLException(java.sql.SQLException) SQLServerDataSource(com.microsoft.sqlserver.jdbc.SQLServerDataSource) ExecutorService(java.util.concurrent.ExecutorService) AbstractTest(com.microsoft.sqlserver.testframework.AbstractTest) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Example 4 with SQLServerDataSource

use of com.microsoft.sqlserver.jdbc.SQLServerDataSource in project mssql-jdbc by Microsoft.

the class ConnectionDriverTest method testConnectionClosed.

@Test
public void testConnectionClosed() throws SQLException {
    assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), "Skipping test case on Azure SQL.");
    SQLServerDataSource mds = new SQLServerDataSource();
    mds.setURL(connectionString);
    Connection con = mds.getConnection();
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    boolean exceptionThrown = false;
    try {
        stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG");
    } catch (Exception e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown, "Expected exception is not thrown.");
    // check to make sure that connection is closed.
    assertTrue(con.isClosed(), "Connection is not closed.");
}
Also used : SQLServerDataSource(com.microsoft.sqlserver.jdbc.SQLServerDataSource) Statement(java.sql.Statement) Connection(java.sql.Connection) PooledConnection(javax.sql.PooledConnection) SQLServerConnection(com.microsoft.sqlserver.jdbc.SQLServerConnection) ISQLServerConnection(com.microsoft.sqlserver.jdbc.ISQLServerConnection) DBConnection(com.microsoft.sqlserver.testframework.DBConnection) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLException(java.sql.SQLException) AbstractTest(com.microsoft.sqlserver.testframework.AbstractTest) Test(org.junit.jupiter.api.Test)

Example 5 with SQLServerDataSource

use of com.microsoft.sqlserver.jdbc.SQLServerDataSource in project mssql-jdbc by Microsoft.

the class ConnectionDriverTest method testDataSource.

/**
 * test SSL properties with SQLServerDataSource
 */
@Test
public void testDataSource() {
    SQLServerDataSource ds = new SQLServerDataSource();
    ds.setUser("User");
    ds.setPassword("sUser");
    ds.setApplicationName("User");
    ds.setURL("jdbc:sqlserver://" + randomServer + ";packetSize=512");
    String trustStore = "Store";
    String trustStorePassword = "pwd";
    ds.setTrustStore(trustStore);
    ds.setEncrypt(true);
    ds.setTrustStorePassword(trustStorePassword);
    ds.setTrustServerCertificate(true);
    assertEquals(trustStore, ds.getTrustStore(), "Values are different");
    assertEquals(true, ds.getEncrypt(), "Values are different");
    assertEquals(true, ds.getTrustServerCertificate(), "Values are different");
}
Also used : SQLServerDataSource(com.microsoft.sqlserver.jdbc.SQLServerDataSource) AbstractTest(com.microsoft.sqlserver.testframework.AbstractTest) Test(org.junit.jupiter.api.Test)

Aggregations

SQLServerDataSource (com.microsoft.sqlserver.jdbc.SQLServerDataSource)26 Test (org.junit.jupiter.api.Test)22 AbstractTest (com.microsoft.sqlserver.testframework.AbstractTest)19 Connection (java.sql.Connection)19 SQLException (java.sql.SQLException)14 SQLServerConnection (com.microsoft.sqlserver.jdbc.SQLServerConnection)9 ISQLServerConnection (com.microsoft.sqlserver.jdbc.ISQLServerConnection)7 DBConnection (com.microsoft.sqlserver.testframework.DBConnection)7 Statement (java.sql.Statement)7 PooledConnection (javax.sql.PooledConnection)7 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)6 ISQLServerDataSource (com.microsoft.sqlserver.jdbc.ISQLServerDataSource)5 ResultSet (java.sql.ResultSet)5 BufferedReader (java.io.BufferedReader)3 InputStreamReader (java.io.InputStreamReader)3 CallableStatement (java.sql.CallableStatement)3 SQLServerCallableStatement (com.microsoft.sqlserver.jdbc.SQLServerCallableStatement)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ObjectOutput (java.io.ObjectOutput)2 ObjectOutputStream (java.io.ObjectOutputStream)2