Connecting to CloudSQL from App Engine (Second Generation CloudSQL) GO - google-app-engine

Love the Stack, My first post out of complete frustration. Thanks for you comments!
Created App Engine Project
Created Second Generation MySQL Instance in my App Engine Project
Created Database in the MySQL Instance
In App Engine, I activate the --> Google Cloud Shell <--. ( I am working at a command prompt in my console.cloud.google.com)
I have copied this basic GO program to connect to my MySQL instance.
I build it and run it.
go build mysqlexample.go
./mysqlexample
I have not been able to achieve a successful connection. You can see all the various connection strings that I have tried and to the right of them is the response I get.
I can connect from my local windows machine using mysql admin.
Help?
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
const dbIP = "104.xxx.xx.x"
const dbInstanceName = "esp-1-dev:us-central1:espdev"
const dbName = "servpro"
const dbUserName = "root"
const dbPassword = "xxxxxxx"
const dbOpenString = dbUserName + ":" + dbPassword + "#/" + dbInstanceName + "/" + dbName //GETS RESPONSE default addr for network 'AppEngine:Zone:Project' unknown
//const dbOpenString = dbUserName + "#cloudsql(" + dbInstanceName + ")/" + dbName //GETS RESPONSE dial cloudsql: unknown network cloudsql
//const dbOpenString = dbUserName + "#/" //+ "?parseTime=true&loc=UTC" //GETS RESPONSE getsockopt: connection refused
//const dbOpenString = dbUserName + ":" + dbPassword + "#tcp(" + dbIP + ":3306)/" + dbName //GETS RESPONSE dial tcp 104.xxx.xxx.x:3306: getsockopt: connection timed out
// Got this from stack overflow. GoDocs are not updated to reflect 2nd Gen databases.
// http://stackoverflow.com/questions/38890022/tls-requested-but-server-does-not-support-tls-error-with-google-cloud-sql-2nd
//user:password#cloudsql(copiedPastedInstanceConnectionName)/d‌​atabaseName?charset=‌​charset&collation=co‌​llation&tls=tlsConfi‌​gName&parseTime=true
//First Generation Connection String
//username:password#cloudsql(appID:CloudSQLInstance)/databasename?parseTime=true&loc=UTC
db, err := sql.Open("mysql", dbOpenString);
defer db.Close()
log.Println("Attempting Ping of database....")
err = db.Ping()
if err != nil {
log.Println("db.Ping() failed: " + dbOpenString)
log.Println(err)
} else {
log.Println("Success!")
}
}

The following are the correct connection strings, but they differ depending on which version of App Engine you are connecting from.
App Engine Standard:
user:password#cloudsql(INSTANCE_CONNECTION_NAME)/dbname
App Engine Flexible:
user:password#unix(/cloudsql/INSTANCE_CONNECTION_NAME)/dbname

If you are migrating to the second generation Go App Engine (Golang 1.11) change your connection string from:
user:password#cloudsql(instanceID)/db
to
user:password#unix(/cloudsql/instanceID)/db

https://cloud.google.com/appengine/docs/flexible/go/using-cloud-sql
For new people to GO, App Engine and CloudSQL just writing the simplest GO program to connect and communicate with your CloudSQL 2nd Gen database is frustrating!
You have choices to make, App Eng or App Eng Flex, SQL 1st or 2nd Gen.... Depending on the combination connection strings are different. All of google's documentation when you search drives you to first gen SQL and App Engine without flex because this is what is predominantly in production. Make sure you are reading Flex documentation if you are doing that. Make sure you are reading 2nd Gen docs if doing that. Sometimes they are entirely different docs, sometimes the documentation is stacked on a page and you have to goto the bottom to see about the newer stuff 2nd gen sql and app eng flex.
CloudShell is tricky, I still cannot compile GO and talk to SQL 2nd here. I am successfully talking to cloud sql 2nd gen from a deployed app engine flex WITH A SQL PROXY RUNNING, you have to use SQL PROXY. You have to go thru the setup for this create users on appengine and SQL.
This is my working program.
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
"fmt"
"net/http"
)
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
}
func main() {
http.HandleFunc("/", handle)
http.HandleFunc("/_cloudshellProxy/_ah/health", healthCheckHandler)
log.Print("Listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handle(w http.ResponseWriter, r *http.Request) {
const dbIP = "104.xxx.xxx.x"
const dbInstanceName = "projectname:us-central1:sqlinstance"
const dbName = "servxxx"
const dbUserName = "sqlproxysuser"
const dbPassword = "xxxRockxxx"
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
fmt.Fprint(w, "Hello SQL! Hello?")
fmt.Fprint(w, "\n")
const dbOpenString = dbUserName + ":" + dbPassword + "#unix(/cloudsql/" + dbInstanceName + ")/" + dbName
//const dbOpenString = dbUserName + ":" + dbPassword + "#cloudsql(" + dbInstanceName + ")/" + dbName
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=- SQL OPEN Statement, per docs, DOES NOT return an error ever
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
db, err := sql.Open("mysql", dbOpenString);
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Fprint(w, "Failed Connection" + " " + dbOpenString)
fmt.Fprint(w, "\n")
fmt.Fprint(w, err)
return
} else {
fmt.Fprint(w, "SUCCESSFUL CONNECTION" + " " + dbOpenString)
fmt.Fprint(w, "\n")
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS exercisecloudsql101 (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, description TEXT, PRIMARY KEY (id))")
if err != nil {
fmt.Fprint(w, "CREATE TABLE failed:")
fmt.Fprint(w, "\n")
fmt.Fprint(w, err)
fmt.Fprint(w, "\n")
} else {
fmt.Fprint(w, "SUCCESSFUL CreateTable" + " " + dbOpenString)
fmt.Fprint(w, "\n")
}
}

Have run in to the same problem of connecting to a cloud SQL instance. One variant that I got working on my windows localhost environment is below. The IP of my localhost needs to be added to Authorized networks for the db instance.
Windows localhost connect over tcp:
user:password#tcp(104.xxx.xxx.xxx:3306)/dbname

Related

What protocol does SnowFlake JDBC driver use?

I'm trying to find out what protocol the SnowFlake JDBC library uses to communicate with SnowFlake. I see hints here and there that it seems to be using HTTPS as the protocol. Is this true?
To my knowledge, other JDBC libraries like for example for Oracle or PostgreSQL use the lower level TCP protocol to communicate with their database servers, and not the application-level HTTP(S) protocol, so I'm confused.
My organization only supports securely routing http(s)-based communication. Can I use this snowflake jdbc library then?
I have browsed all documentation that I could find, but wasn't able to answer this question.
My issue on GitHub didn't get an answer either.
Edit: Yes, I've seen this question, but I don't feel that it answers my question. SSL/TLS is an encryption, but that doesn't specify the data format.
It looks like the jdbc driver uses HTTP Client HttpUtil.initHttpClient(httpClientSettingsKey, null);, as you can see in here
The HTTP Utility Class is available here
Putting an excerpt of the session open method here in case the link goes bad/dead.
/**
* Open a new database session
*
* #throws SFException this is a runtime exception
* #throws SnowflakeSQLException exception raised from Snowflake components
*/
public synchronized void open() throws SFException, SnowflakeSQLException {
performSanityCheckOnProperties();
Map<SFSessionProperty, Object> connectionPropertiesMap = getConnectionPropertiesMap();
logger.debug(
"input: server={}, account={}, user={}, password={}, role={}, database={}, schema={},"
+ " warehouse={}, validate_default_parameters={}, authenticator={}, ocsp_mode={},"
+ " passcode_in_password={}, passcode={}, private_key={}, disable_socks_proxy={},"
+ " application={}, app_id={}, app_version={}, login_timeout={}, network_timeout={},"
+ " query_timeout={}, tracing={}, private_key_file={}, private_key_file_pwd={}."
+ " session_parameters: client_store_temporary_credential={}",
connectionPropertiesMap.get(SFSessionProperty.SERVER_URL),
connectionPropertiesMap.get(SFSessionProperty.ACCOUNT),
connectionPropertiesMap.get(SFSessionProperty.USER),
!Strings.isNullOrEmpty((String) connectionPropertiesMap.get(SFSessionProperty.PASSWORD))
? "***"
: "(empty)",
connectionPropertiesMap.get(SFSessionProperty.ROLE),
connectionPropertiesMap.get(SFSessionProperty.DATABASE),
connectionPropertiesMap.get(SFSessionProperty.SCHEMA),
connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE),
connectionPropertiesMap.get(SFSessionProperty.VALIDATE_DEFAULT_PARAMETERS),
connectionPropertiesMap.get(SFSessionProperty.AUTHENTICATOR),
getOCSPMode().name(),
connectionPropertiesMap.get(SFSessionProperty.PASSCODE_IN_PASSWORD),
!Strings.isNullOrEmpty((String) connectionPropertiesMap.get(SFSessionProperty.PASSCODE))
? "***"
: "(empty)",
connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY) != null
? "(not null)"
: "(null)",
connectionPropertiesMap.get(SFSessionProperty.DISABLE_SOCKS_PROXY),
connectionPropertiesMap.get(SFSessionProperty.APPLICATION),
connectionPropertiesMap.get(SFSessionProperty.APP_ID),
connectionPropertiesMap.get(SFSessionProperty.APP_VERSION),
connectionPropertiesMap.get(SFSessionProperty.LOGIN_TIMEOUT),
connectionPropertiesMap.get(SFSessionProperty.NETWORK_TIMEOUT),
connectionPropertiesMap.get(SFSessionProperty.QUERY_TIMEOUT),
connectionPropertiesMap.get(SFSessionProperty.TRACING),
connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE),
!Strings.isNullOrEmpty(
(String) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE_PWD))
? "***"
: "(empty)",
sessionParametersMap.get(CLIENT_STORE_TEMPORARY_CREDENTIAL));
HttpClientSettingsKey httpClientSettingsKey = getHttpClientKey();
logger.debug(
"connection proxy parameters: use_proxy={}, proxy_host={}, proxy_port={}, proxy_user={},"
+ " proxy_password={}, non_proxy_hosts={}, proxy_protocol={}",
httpClientSettingsKey.usesProxy(),
httpClientSettingsKey.getProxyHost(),
httpClientSettingsKey.getProxyPort(),
httpClientSettingsKey.getProxyUser(),
!Strings.isNullOrEmpty(httpClientSettingsKey.getProxyPassword()) ? "***" : "(empty)",
httpClientSettingsKey.getNonProxyHosts(),
httpClientSettingsKey.getProxyProtocol());
// TODO: temporarily hardcode sessionParameter debug info. will be changed in the future
SFLoginInput loginInput = new SFLoginInput();
loginInput
.setServerUrl((String) connectionPropertiesMap.get(SFSessionProperty.SERVER_URL))
.setDatabaseName((String) connectionPropertiesMap.get(SFSessionProperty.DATABASE))
.setSchemaName((String) connectionPropertiesMap.get(SFSessionProperty.SCHEMA))
.setWarehouse((String) connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE))
.setRole((String) connectionPropertiesMap.get(SFSessionProperty.ROLE))
.setValidateDefaultParameters(
connectionPropertiesMap.get(SFSessionProperty.VALIDATE_DEFAULT_PARAMETERS))
.setAuthenticator((String) connectionPropertiesMap.get(SFSessionProperty.AUTHENTICATOR))
.setOKTAUserName((String) connectionPropertiesMap.get(SFSessionProperty.OKTA_USERNAME))
.setAccountName((String) connectionPropertiesMap.get(SFSessionProperty.ACCOUNT))
.setLoginTimeout(loginTimeout)
.setAuthTimeout(authTimeout)
.setUserName((String) connectionPropertiesMap.get(SFSessionProperty.USER))
.setPassword((String) connectionPropertiesMap.get(SFSessionProperty.PASSWORD))
.setToken((String) connectionPropertiesMap.get(SFSessionProperty.TOKEN))
.setPasscodeInPassword(passcodeInPassword)
.setPasscode((String) connectionPropertiesMap.get(SFSessionProperty.PASSCODE))
.setConnectionTimeout(httpClientConnectionTimeout)
.setSocketTimeout(httpClientSocketTimeout)
.setAppId((String) connectionPropertiesMap.get(SFSessionProperty.APP_ID))
.setAppVersion((String) connectionPropertiesMap.get(SFSessionProperty.APP_VERSION))
.setSessionParameters(sessionParametersMap)
.setPrivateKey((PrivateKey) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY))
.setPrivateKeyFile((String) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE))
.setPrivateKeyFilePwd(
(String) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE_PWD))
.setApplication((String) connectionPropertiesMap.get(SFSessionProperty.APPLICATION))
.setServiceName(getServiceName())
.setOCSPMode(getOCSPMode())
.setHttpClientSettingsKey(httpClientSettingsKey);
// propagate OCSP mode to SFTrustManager. Note OCSP setting is global on JVM.
HttpUtil.initHttpClient(httpClientSettingsKey, null);
SFLoginOutput loginOutput =
SessionUtil.openSession(loginInput, connectionPropertiesMap, tracingLevel.toString());
isClosed = false;
authTimeout = loginInput.getAuthTimeout();
sessionToken = loginOutput.getSessionToken();
masterToken = loginOutput.getMasterToken();
idToken = loginOutput.getIdToken();
mfaToken = loginOutput.getMfaToken();
setDatabaseVersion(loginOutput.getDatabaseVersion());
setDatabaseMajorVersion(loginOutput.getDatabaseMajorVersion());
setDatabaseMinorVersion(loginOutput.getDatabaseMinorVersion());
httpClientSocketTimeout = loginOutput.getHttpClientSocketTimeout();
masterTokenValidityInSeconds = loginOutput.getMasterTokenValidityInSeconds();
setDatabase(loginOutput.getSessionDatabase());
setSchema(loginOutput.getSessionSchema());
setRole(loginOutput.getSessionRole());
setWarehouse(loginOutput.getSessionWarehouse());
setSessionId(loginOutput.getSessionId());
setAutoCommit(loginOutput.getAutoCommit());
// Update common parameter values for this session
SessionUtil.updateSfDriverParamValues(loginOutput.getCommonParams(), this);
String loginDatabaseName = (String) connectionPropertiesMap.get(SFSessionProperty.DATABASE);
String loginSchemaName = (String) connectionPropertiesMap.get(SFSessionProperty.SCHEMA);
String loginRole = (String) connectionPropertiesMap.get(SFSessionProperty.ROLE);
String loginWarehouse = (String) connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE);
if (loginDatabaseName != null && !loginDatabaseName.equalsIgnoreCase(getDatabase())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
"Database",
loginDatabaseName,
getDatabase()));
}
if (loginSchemaName != null && !loginSchemaName.equalsIgnoreCase(getSchema())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
"Schema",
loginSchemaName,
getSchema()));
}
if (loginRole != null && !loginRole.equalsIgnoreCase(getRole())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP, "Role", loginRole, getRole()));
}
if (loginWarehouse != null && !loginWarehouse.equalsIgnoreCase(getWarehouse())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
"Warehouse",
loginWarehouse,
getWarehouse()));
}
// start heartbeat for this session so that the master token will not expire
startHeartbeatForThisSession();
}

can't connect to postgresql database "database doesn´t exist"

I have a Go app that connects with a postgres database through the driver called "github.com/lib/pq".
I make a connection with a database called godb, and the function Open() works correctly, but when I check errors with db.Ping(), it tells me the database doesn´t exist, although I have created it in pg Admin and the name and the password are well written. I have tried to check if the connection string is correct, I have tried to create a new database and connect it but it gives the same error. I have also tried to disconnect and reconnect the database and it doesn't work.
package main
import (
"database/sql"
"fmt"
"log"
"sync"
//driver of the database
_ "github.com/lib/pq"
)
var (
db *sql.DB
once sync.Once
)
func NewPostgresDB() {
once.Do(func() {
var err error
db, err = sql.Open("postgres",
"postgres://postgres:/*password of the database*/#localhost:5432/godb?sslmode=disable")
if err != nil {
log.Fatalf("There is an error in the connction string %v", err)
}
if err = db.Ping(); err != nil {
log.Fatalf("There was an error connecting to the database %v", err)
}
})
fmt.Println("connection succeeded")
}
this is the error it exactly returns (it's in Spanish):
pq: no existe la base de datos �godb�
exit status 1

Golang Unable to get instances from Sql Server Browser on host

I can't provide an Mssql connection. What's the problem?
Unable to get instances from Sql Server Browser on host DESKTOP-A:
read udp [8c32%vEthernet (Default Switch)]:55199->[8c32%vEthernet
(Default Switch)]:1434: i/o timeout
package main
import (
"database/sql"
"flag"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
)
func main() {
var (
userid = flag.String("U", "loginx", "login_id")
password = flag.String("P", "1", "password")
server = flag.String("S", "DESKTOP-A\\SQLEXPRESS", "server_name[\\instance_name]")
database = flag.String("d", "test", "db_name")
)
flag.Parse()
dsn := "server=" + *server + ";user id=" + *userid + ";password=" + *password + ";database=" + *database
db, err := sql.Open("mssql", dsn)
if err != nil {
fmt.Println("Cannot connect: ", err.Error())
return
}
err = db.Ping()
if err != nil {
fmt.Println("Cannot connect: ", err.Error())
return
}
defer db.Close()
}
you can use sqlserver://user:pass#host:1433/instance?database=dbname as the DSN.
I'd like to point out that the default port the Go driver uses is 1434, which is the UDP port for SQLServer. However, in my experience, the server itself almost never uses that port by default. So by supplying the default TCP port, 1433, got it to work for me.

google apps script jbdc sql server database connection string error

I'm trying to connect to my local sql server database at my home network using the code that I found from this site Querying SQL Server with Google Apps Script via JDBC about 3 years ago which was marked being correct. However, I get the error message "We're sorry, a server error occurred. Please wait a bit and try again.". This error is from line 2 where the connection string is defined. I retried several times, but I always get the same error. When I searched this error, it seems like it could be too many things and I was not able to find any answers for my issue. Thanks.
This was the code that was marked being correct:
function readAzure() {
var conn = Jdbc.getConnection("jdbc:sqlserver://XYZ.database.windows.net:1433;databaseName=MYDATABSENAME","USERNAME","PASSWORD");
var stmt = conn.createStatement();
var rs = stmt.executeQuery("select * from helloworld");
var doc = SpreadsheetApp.create('azure');
var cell = doc.getRange('a1');
var row = 0;
while(rs.next()) {
cell.offset(row, 0).setValue(rs.getString(1));
cell.offset(row, 1).setValue(rs.getString(2));
row++;
}
rs.close();
stmt.close();
conn.close();
}
I also found another connection string code and when I try this format I get the same error.
var conn = Jdbc.getConnection("jdbc:sqlserver://IP-address:1433;" + "databaseName=DBName;user=username;password=password;");
Based on this documentation, you need to ensure that your database accepts connections from any of Apps Script's IP addresses. These are the address ranges you'll need to whitelist.
64.18.0.0 - 64.18.15.255
64.233.160.0 - 64.233.191.255
66.102.0.0 - 66.102.15.255
66.249.80.0 - 66.249.95.255
72.14.192.0 - 72.14.255.255
74.125.0.0 - 74.125.255.255
173.194.0.0 - 173.194.255.255
207.126.144.0 - 207.126.159.255
209.85.128.0 - 209.85.255.255
216.239.32.0 - 216.239.63.255
Also, from the documentation link above, there is a sample code that you can follow to set up external database via JDBC.
Here is a code that demonstrates how to write a single record to the database as well as a batch of 500 records.
// Replace the variables in this block with real values.
var address = 'database_IP_address';
var user = 'user_name';
var userPwd = 'user_password';
var db = 'database_name';
var dbUrl = 'jdbc:mysql://' + address + '/' + db;
// Write one row of data to a table.
function writeOneRecord() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(guestName, content) values (?, ?)');
stmt.setString(1, 'First Guest');
stmt.setString(2, 'Hello, world');
stmt.execute();
}
// Write 500 rows of data to a table in a single batch.
function writeManyRecords() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
conn.setAutoCommit(false);
var start = new Date();
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(guestName, content) values (?, ?)');
for (var i = 0; i < 500; i++) {
stmt.setString(1, 'Name ' + i);
stmt.setString(2, 'Hello, world ' + i);
stmt.addBatch();
}
var batch = stmt.executeBatch();
conn.commit();
conn.close();
var end = new Date();
Logger.log('Time elapsed: %sms for %s rows.', end - start, batch.length);
}
For more information, just read through to this documentation and check this thread and related SO question.

Data encryption issues with Oracle Advanced Security

I have used Oracle Advanced Security to encrypt data during data transfer. I have successfully configured ssl with below parameters and I have restarted the instance. I am retrieving data from a Java class given below. But I could read the data without decrypting, the data is not getting encrypted.
Environment:
Oragle 11g database
SQLNET.AUTHENTICATION_SERVICES= (BEQ, TCPS, NTS)
SSL_VERSION = 0
NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
SSL_CLIENT_AUTHENTICATION = FALSE
WALLET_LOCATION =
(SOURCE =
(METHOD = FILE)
(METHOD_DATA =
(DIRECTORY = C:\Users\kcr\Oracle\WALLETS)
)
)
SSL_CIPHER_SUITES= (SSL_RSA_EXPORT_WITH_RC4_40_MD5)
Java class:
try{
Properties properties = Utils.readProperties("weka/experiment/DatabaseUtils.props");
// Security.addProvider(new oracle.security.pki.OraclePKIProvider()); //Security syntax
String url = "jdbc:oracle:thin:#(DESCRIPTION =\n" +
" (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))\n" +
" (CONNECT_DATA =\n" +
" (SERVER = DEDICATED)\n" +
" (SERVICE_NAME = sal)\n" +
" )\n" +
" )";
java.util.Properties props = new java.util.Properties();
props.setProperty("user", "system");
props.setProperty("password", "weblogic");
// props.setProperty("javax.net.ssl.trustStore","C:\\Users\\kcr\\Oracle\\WALLETS\\ewallet.p12");
// props.setProperty("oracle.net.ssl_cipher_suites","SSL_RSA_EXPORT_WITH_RC4_40_MD5");
// props.setProperty("javax.net.ssl.trustStoreType","PKCS12");
//props.setProperty("javax.net.ssl.trustStorePassword","welcome2");
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(url, props);
/*8 OracleDataSource ods = new OracleDataSource();
ods.setUser("system");
ods.setPassword("weblogic");
ods.setURL(url);
Connection conn = ods.getConnection();*/
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select * from iris");
///////////////////////////
while(rset.next()) {
for (int i=1; i<=5; i++) {
System.out.print(rset.getString(i));
}
}
Are you expecting that your SELECT statement would return encrypted data and that your System.out.print calls would result in encrypted output going to the screen? If so, that's not the way advanced security works-- Advanced Security allows you to encrypt data over the wire but the data is unencrypted in the SQLNet stack. Your SELECT statement, therefore, would always see the data in an unencrypted state. You would need to do a SQLNet trace or use some sort of packet sniffer to see the encrypted data flowing over the wire.
You'll find the documentation in "SSL With Oracle JDBC Thin Driver".
In particular you should probably use PROTOCOL = TCPS instead of PROTOCOL = TCP. I'd also suggest using a stronger cipher suite (and avoid the anonymous ones, since with them you don't verify the identity of the remote server).

Resources