Connect to SQL server using groovy - sql-server

I am using sqlserver express , i want to do a connection from groovy and show the data on the console now i have an error and its not connecting. I decided to show what i have on here so we can debug together,
Code looks like this :
package com.connectgroovy
import groovy.sql.Sql
class GroovyConnectMssqlExample {
static main(args)
{
def conn = Sql.newInstance("jdbc:sqlserver://localhost:1433","DESKTOP-V2G35NU\\SQLEXPRESS","com.microsoft.sqlserver.jdbc.SQLServerDriver")
conn.eachRow("select * from [bonitasoft_jsonTest].[dbo].[people_data]"){
println "${it.fullname} | ${it.perdiem}"
}
}
}
I get this as an exception error :
Caught: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'DESKTOP-V2G35NU\SQLEXPRESS'.
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'DESKTOP-V2G35NU\SQLEXPRESS'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2529)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1905)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1893)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1045)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at com.connectgroovy.GroovyConnectMssqlExample.main(GroovyConnectMssqlExample.groovy:9)
What am i not doing right?
PS
I put the sqljdbc4.jar as a referenced Library. in eclipse

Connection URL - The url typically contains which server to connect to, what port and which database schema to work with. Example: "jdbc:mysql://localhost:3306/test"
Username and password - The credentials for authenticating the connection. Example: username = user and password = password.
JDBC Driver Class - The JDBC driver class to use to connect to the database. Example for MySQL case: "com.microsoft.sqlserver.jdbc.SQLServerDriver"
def sql = Sql.newInstance("jdbc:sqlserver://localhost:1433/test",
"user", "password", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
For Window Authentication
def sql =Sql.newInstance("jdbc:sqlserver://localhost;Database=myDB;integratedSecurity=true","com.microsoft.sqlserver.jdbc.SQLServerDriver")

Related

SQLServerException: Login failed for user 'test#abc.com'

I am using microsoft jdbc for connecting to azure sql. Below is the java code :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = String.format("jdbc:sqlserver://***.database.windows.net:1433;database=<my database name>;user=test#abc.com#xyz-url-dev-123abc;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
Getting error SQLServerException: Login failed for user 'test#abc.com' (user name is changed with same format).
Is # causing problem ? Because for user parameter I am sending 'user#url' which is test#abc.com#xyz-url-dev-123abc
Let me know if I am making sense!

SOAP UI: Getting Error getting response; null when trying to connect to Microsoft SQL Server

I am trying to connect to Microsoft sql server 2018 from SOAP ui by creating a JDBC Request, but geeting Error getting response; null in logs.
Note: i have added mssql-jdbc-7.2.2.jre11 to ext folder in SOAP UI.
External Folder
SOAP-UI 5.5 JDBC Request
Driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
Connection String: jdbc:microsoft:sqlserver://localhost; databaseName=Amazon;integratedSecurity=true;
Query: select * from userbase
I don't use the JDBC step in SoapUI, but rather do my database steps in a Groovy script test step.
I also have had more success with the jTDS driver for MS-SQL.
A sample connection string with domain authentication/integrated security is:
def conn = Sql.newInstance("""jdbc:jtds:sqlserver://SERVERNAME:1433/dbname;
useLOBs=false;
instance=SERVERNAME;
autoCommit=true;
useNTLMv2=true;
domain=MYDOMAIN",
"MyUser", "MyPassword", "net.sourceforge.jtds.jdbc.Driver""")
Then:
myDB.eachRow("select * from userbase;"){
//do something with the data
}
I would also suggest that you select specific columns, not *
From there you can put the data in a file or populate property values or whatever.

Can't connect to the MS SQL Server 2008 database instance using Hibernate

I'm trying to connect to the MSSQL Server using Hibernate. Code I've wrote is ok, when I try to connect to the "normal" database, but I'm always getting exception for one database, which has instance.
Error is:
2020-03-06 15:07:01.755 WARN com.mchange.v2.async.ThreadPoolAsynchronousRunner: com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector#12fa2433 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
2020-03-06 15:07:01.758 WARN com.mchange.v2.async.ThreadPoolAsynchronousRunner: com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector#12fa2433 -- APPARENT DEADLOCK!!! Complete Status:
Managed Threads: 3
Active Threads: 3
Active Tasks:
com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask#5d00c227
on thread: C3P0PooledConnectionPoolManager[identityToken->2sk2t6a81cvnu23110fpe1|11389053]-HelperThread-#0
com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask#1e98ae08
on thread: C3P0PooledConnectionPoolManager[identityToken->2sk2t6a81cvnu23110fpe1|11389053]-HelperThread-#2
com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask#6c17f8ef
on thread: C3P0PooledConnectionPoolManager[identityToken->2sk2t6a81cvnu23110fpe1|11389053]-HelperThread-#1
Pending Tasks:
com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask#6665ca79
com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask#3d2f3d68
Pool thread stack traces:
Thread[C3P0PooledConnectionPoolManager[identityToken->2sk2t6a81cvnu23110fpe1|11389053]-HelperThread-#0,5,main]
java.lang.Thread.sleep(Native Method)
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2336)
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2067)
com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1204)
com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:825)
com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175)
com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220)
com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206)
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203)
com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138)
com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125)
com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44)
com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870)
com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696)
Using the same login password I can connect to the database but not programmatically, i.e. using sqlcmd.
How I create connection:
public synchronized static SessionFactory getSessionFactory(Logger log, DbServer dbServer, String dbName) {
String url = String.format("jdbc:sqlserver://%s:%d;databaseName=%s", dbServer.getServerName(), dbServer.getPort(), dbName);
return new Configuration().configure()
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
.setProperty("hibernate.default_schema", "dbo")
.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect")
.setProperty("hibernate.connection.username", dbServer.getLogin())
.setProperty("hibernate.connection.password", dbServer.getPassword())
.setProperty("hibernate.connection.url", url)
.buildSessionFactory();
}
dbServer.getServerName() returns "serverName\dbInstance", port is 1433, dbName is master.
Using Microsoft SQL Management Studio I can connect using the same login/password so I'm pretty sure that it's problem with configuration - I'm using sys admin (sa) so it's not permissions issue.
Solution was not to use port when I try connect to database. So connection string looks like this:
String url = String.format("jdbc:sqlserver://%s;instanceName=%s;databaseName=%s", dbServer.getServerName(), dbServer.getInstanceName(), dbName);

Why do i get this error when i connect snowflake and python

This is the error i get when i connect to snowflake via python?
OperationalError: 250003: Failed to execute request: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])",)
I connect using:
ctx = snowflake.connector.connect(
user='JoeBloggs',
password='pwd',
account='JoeBloggs',
database='DEV_DATA'
)
do i need to feed in other paramters such as port, host, etc how did i find what these are?
I think your value for 'account' needs to be modified. It looks like you're using your username there, but it should be the Snowflake account. This should be the portion of the URL that you connect directly to that precedes the snowflakecomputing.com portion. For example, 'xy12345.east-us-2.azure'.
My initial thoughts are that the error indicates a firewall or proxy issue. In particular, a proxy might intercept Snowflake's SSL certificate and replace it with their own. The best way to resolve this is to ensure the certificate is trusted in the proxy and the proxy is configured as per Snowflake's documentation so that the Snowflake certificate can pass through.
The documentation below has more information on using a proxy with SnowSQL. You can pass along the error with issuer details to your network engineer and can request to whitelist the required URLs (documentation also below outlining the whitelisting requirements). You can use the SYSTEM$WHITELIST function to get all the URLs to whitelist in a proxy or firewall for your account.
https://docs.snowflake.net/manuals/user-guide/snowsql-start.html#using-a-proxy-server
https://docs.snowflake.net/manuals/user-guide/hostname-whitelist.html
First, install Snowflake python connector .pip3 install snowflake-python-connector.
Can you try with code below:
------------------------------------------------------
import snowflake.connector
PASSWORD = '*****'
USER = '<UNAME>'
ACCOUNT = '<ACCNTNAME>'
WAREHOUSE = '<WHNAME>'
DATABASE = '<DBNAME>'
SCHEMA = 'PUBLIC'
print("Connecting...")
con = snowflake.connector.connect(
user=USER,
password=PASSWORD,
account=ACCOUNT,
warehouse=WAREHOUSE,
database=DATABASE,
schema=SCHEMA
)
con.cursor().execute("USE WAREHOUSE " + WAREHOUSE)
con.cursor().execute("USE DATABASE " + DATABASE)
try:
result = con.cursor().execute("Select * from <TABLENAME>")
result_list = result.fetchall()
print(result_list)
finally:
con.cursor().close()
con.cursor().close()
---------------------------------------------------

How to Connect Airflow to oracle database

I am trying to create a connection to an oracle db instance (oracle:thin) using Airflow.
According to their documentation I entered my hostname followed by port number and SID:
Host: example.com:1524/sid
filled other fields as:
Conn Type: Oracle
Schema: username ( documentation says: use your username for schema )
Login: username
Password: * * *
After connection is setup, it gives the save error code for every query that I tried to execute (ORA-12514).
It seems like oracle doesn't let airflow to connect:
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
Has someone experienced the same problem before. I mean connecting to a database shouldn't be a problem for a big platform like this. Or I am probably doing something wrong. Thanks
Version: Airflow v1.7.0, Oracle11g
EDIT:
I am using the same hostname which I use in Oracle SQLDeveloper client:
After digging into the source code, this is what finally how it worked for me:
Conn Type: Oracle
Host: example.com
schema: username
login: username
port: port number
extra: {"sid": "my sid", "dsn": "example.com"}
You have a problem in your connection settings, either your setting is not loading properly to the oracle hook or you are missing a python package that save/load your connection settings. You can test it by hard coding your credentials.
https://github.com/airbnb/airflow/blob/master/airflow/hooks/oracle_hook.py
conn = self.get_connection(self.oracle_conn_id)
dsn = conn.extra_dejson.get('dsn', None)
sid = conn.extra_dejson.get('sid', None)
service_name = conn.extra_dejson.get('service_name', None)
if dsn and sid and not service_name:
dsn = cx_Oracle.makedsn(dsn, conn.port, sid)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
elif dsn and service_name and not sid:
dsn = cx_Oracle.makedsn(dsn, conn.port, service_name=service_name)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
else:
conn = cx_Oracle.connect(conn.login, conn.password, conn.host)
for service name usage, if you leave (port, schema and extra) empty, you can put the full oracle connection descriptor under Host:
(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = mysidname)))
this worked for me in extra field
{ "dsn":"192.168.x.x" , "service_name":"some.service.name" }
I get from https://github.com/apache/airflow/blob/master/airflow/hooks/oracle_hook.py#L49
If anyone just does not see the connection in the Ad hoc query dropdown - you need to install the adapter: pip install cx_Oracle on the airflow server.

Resources