SQL Connection Error with Spring Boot - sql-server

I am getting this "SQL state [null]; error code [0]; The connection is closed.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed." Error when using springBootVersion = '1.5.4.RELEASE', JDBC driver version 6, and SQLServer 2008R2, using database mirroring. My connection settings:
spring:
datasource:
initialize: false
username: user1
password: pass1
type: org.apache.tomcat.jdbc.pool.DataSource
connection-properties:
statementPoolingCacheSize=200;failoverPartner=Server2;applicationName=${sp
ring.application.name}
url: jdbc:sqlserver://Server1;databaseName=DBName
tomcat:
initial-size: 10
max-active: 50
max-idle: 10
max-wait: 1000
validation-query: "SELECT 1"
Can you please help me in determining why this error is occurring?

Tomcat native connection pool didn't work for failover and hikari.HikariDataSource was used.
spring:
datasource:
initialize: false
type: com.zaxxer.hikari.HikariDataSource
username: user1
password: pass1
jdbcUrl: jdbc:sqlserver:/server1;databaseName=DB1;statementPoolingCacheSize=200;failoverPartner=server2;applicationName=${spring.application.name}
dataSourceClassname: com.microsoft.sqlserver.jdbc.SQLServerDataSource
hikari:
pool-name: TimeCommerce
connection-timeout: 1000
leak-detection-threshold: 5000
maximum-pool-size: 40
max-lifetime: 60000
minimum-idle: 20
connection-test-query: SELECT 1
test-on-borrow: true
     test-on-connect: true
     test-on-return: true

Related

Using pymssql to connect to SQL Server in Windows

Pymssql -V:2.2.1
Python -V: 3.8
DB: SQL Server 2008 R2
This is my code:
class read_sql(object):
def __init__(self):
# 服务器名
self.server = HOST_24
# 用户名
self.user = SQL_SERVER_USER
# 密码
self.password = SQL_SERVER_PASSWORD
# 数据库名
self.database = PUBMED_DB
# 连接数据库
try:
self.conn = pymssql.connect(self.server, self.user, self.password, self.database)
# 创建cursor缓冲区,用来存放sql语句
self.cursor = self.conn.cursor()
except Exception as e:
print(e)
raise ValueError('数据库链接实例化出错')
def query(self, query_str):
# 输入query_str查询语句,内容返回到cursor缓冲区内
self.cursor.execute(query_str)
# 接收全部的返回结果行.
row = self.cursor.fetchall()
return row
if __name__ == "__main__":
sql_data = read_sql()
row = sql_data.query("SELECT TOP 1 * FROM JinMo_CheckTable order by id desc")
print(row)
This is my first time connecting to SQL Server!
I get this error:
pymssql._mssql.MSSQLDatabaseException: (18456, b"\xe7\x94\xa8\xe6\x88\xb7 'sa' \xe7\x99\xbb\xe5\xbd\x95\xe5\xa4\xb1\xe8\xb4\xa5\xe3\x80\x82DB-Lib error message 20018, severity 14:
General SQL Server error: Check messages from the SQL Server
DB-Lib error message 20002, severity 9:
Adaptive Server connection failed (192.168.0.24)
DB-Lib error message 20002, severity 9:
Adaptive Server connection failed (192.168.0.24)
Please give me some suggestions - thanks !

Managing Login Timeout Expired errors against SQL Server

I have the next VB.NET code being executed every hour. The code connects to that server and that database and execute some commands, not only on the database MyDatabase, but also on other databases in the same server.
As the user is a sysadmin, it has admin access to all databases without problem.
Dim ConnStr As String
Dim Conn As SqlConnection
Dim cM As SqlCommand
Try
ConnStr = "Server=MyServer;Database=MyDatabase;User Id=MyUsername;Password=MyPassword;Connect Timeout=300"
Dim Conn As New SqlConnection(ConnStr)
cM = New SqlCommand("", Conn) 'The SQL code comes from an script file (*.sql)
cM.CommandTimeout = 1800
cM.Connection = Conn
Conn.Open()
cM.ExecuteNonQuery()
Catch eX As Exception
Dim strError As String = ex.Message
If Not ex.InnerException Is Nothing Then strError &= " | " & ex.InnerException.Message
strError = "Connection Timeout: " & Conn.ConnectionTimeout.ToString & " | " & _
"Command Timeout: " & cM.CommandTimeout.ToString & " | " & _
strError
objLogging.LogErrorStep(JobID, JobName, CurrentStepName, strError)
Finally
If Conn.State = ConnectionState.Open Then Conn.Close()
Conn.Dispose()
End Try
The issue we are experimenting is that some of the runs of this job are failing because of Login Timeout Expired errors:
Connection Timeout: 300 | Command Timeout: 1800 | TCP Provider: Timeout error [258].
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Login timeout expired".
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Unable to complete login process due to delay in prelogin response".
As you can see in the code, I'm saving the errors in a Logging table, and also saving there the current Connection Timeout and the current Command Timeout.
My surprise is that when I'm checking the errors in my Logging table, I can see the elapsed time between the command started time and the command failed time, and the elapsed time has been only 15 seconds, when my Connection Timeout is set to 300. Look at the next image:
As you can see, the difference between the EventStart and the EventStop is about 15 seconds. If the process fails because of a Connection Timeout, and it is set to 300, the elapsed time should be 300, isn't it?
Thanks for your help and comments.
EDIT 2019-05-31
After wait for one more day having set the Connect Timeout = 300 property in the OPEDATASOURCE connectionString, I got a new Login Timeout Expired this afternoon, also just in 15 seconds (See the image)
The connect timeout and CommandTimeout settings apply to the connection from the client to "MyDatabase". Since your SQL Command connects to linked servers, those settings will not automatically be transferred and will have to be configured at the SQL Server level. Note that this change applies immediately and is server wide (T-SQL):
EXEC sp_configure 'remote login timeout', 300;
GO
RECONFIGURE ;
GO
EXEC sp_configure 'remote query timeout', 1800;
GO
RECONFIGURE ;
GO
See these two related MSDN links:
Remote Login Timeout
Remote Query Timeout

R connection to MS SQL

Using R I am trying to connect to MS SQL 2014 on an Azure VM (not windows authentication)
library(RODBC)
conn <- odbcDriverConnect(connection = "Driver=SQL Server;Server=someinternetmachine.cloudapp.net;Database=MyDatabase;Uid=MyUsername;Pwd=MyPassword;")
queryResult <- sqlQuery(conn, "SELECT top 10 * FROM sometable")
With RODBC is there anywhere to do this using just a connection string (no DSN)?
Using the above I get the below errors
Warning messages:
1: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 08001, code 6, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]Specified SQL server not found.
2: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 01000, code 11001, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
3: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
ODBC connection failed
Did you choose public provisioning for the VM in Azure? Additionally, you need to open the ports for SQL Server in Windows Firewall (port number depends on default or named instance). Also, in case of named instance if you are using dynamic ports then SQL Browser also needs to be opened up. More information can be found in the link here.
Managed to get this working with
driver.name <- "SQL Server"
db.name <- "master"
host.name <- "someinternetmachine.cloudapp.net"
port <- ""
server.name <- "someinternetmachine.cloudapp.net"
user.name <- "MyUsername"
pwd <- "MyPassword"
# Use a full connection string to connect
con.text <- paste("DRIVER=", driver.name,
";Database=", db.name,
";Server=", server.name,
";Port=", port,
";PROTOCOL=TCPIP",
";UID=", user.name,
";PWD=", pwd, sep = "")
con1 <- odbcDriverConnect(con.text)
res <- sqlQuery(con1, 'select * from information_schema.tables')
odbcCloseAll()

server properties in loops in Capistrano

I am new to Capistrano.
I need to get the server properties in tasks using a loop. I am using this code:
server 'IP_address', user: 'root', password: 'pass', roles: %w{web}, database: 'production1'
server 'IP_address', user: 'root', password: 'pass', roles: %w{web}, database: 'production2'
task :backup_FilesDatabaseServerfiles do
on roles (:web) do |h|
puts h.database
end
end
How can I fetch database options in the above task?
This should do it.
task :backup_FilesDatabaseServerfiles do
on roles :web do |server|
p server.properties.database
end
end
Per Capistrano 3: use server custom variable in task

Cannot connect to Redshift database with a driver even though play.ap.db.DB can do this for the same driver

I am trying to connect to a redshift server and run some sql commands. Here is the code that I have written:
Class.forName("org.postgresql.Driver")
val url: String = s"jdbc:postgres://${user}:${password}#${host}:${port}/${database}"
val connection: Connection = DriverManager.getConnection(url, user, password)
val statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
val setSearchPathQuery: String = s"set search_path to '${schema}';"
statement.execute(setSearchPathQuery)
But I am getting the following error:
java.sql.SQLException: No suitable driver found for jdbc:postgres://user:password#host:port/database
But when I am using play framework's default database library with the same configuration, then I am able to connect to database successfully. Below is the configuration for the default database:
db.default.driver=org.postgresql.Driver
db.default.url="postgres://username:password#hostname:port/database"
db.default.host="hostname"
db.default.port="port"
db.default.dbname = "database"
db.default.user = "username"
db.default.password = "password"
The problem was with the url. The correct format for the url is:
jdbc:postgresql://hostname:port/database

Resources