Validate SQL Server Connection - sql-server

How i could check if i have connection to an SQL Server with the Connection String known in C#?

using (var connection = new SqlConnection("connectionString"))
{
try
{
connection.Open();
Console.WriteLine("Connection Ok");
}
catch (SqlException)
{
Console.WriteLine("Connection Not Ok");
}
}

I"m not sure if you are asking how to validate a connection string or check to see if a current connection is open If you are trying to check if a current connection is open you can use.
connection.State
ConnectionState Enumeration Values

You can also test it outside of your code by making an UDL file (a text file with extension .UDL). Then right-click it, get the properties and enter the connectionstring details.
Press the "Test Connection" button and then you'll know.

Check the state of the connection.
if (conexion.State == ConnectionState.Closed)
{
conexion.Open();
}

Related

How can I connect my javafx application to my sqlserver?

I am trying to connect to a database when I run my application I am getting the error "com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value".
I have tried changing some of the variables around but cannot figure out where my error is. Can anyone help?
try{
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbURL = "jdbc:sqlserver://[myservername];databaseName=[databasename];user=[enteruserdbhere];password[enterpasswordhere];";
Connection conn = DriverManager.getConnection(dbURL);
Statement statement = conn.createStatement();
conn.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
Try removing the '[]' brackets from the connection string.
The link below shows examples of connection strings for jdbc https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15
You should remove the brackets [ ] for your connection URL.
String server = "localhost";
String dbName = "myDB";
String username = "root";
String pwd = "";
String dbURL = "jdbc:sqlserver://server;databaseName=dbName;user=username;password=pwd;";
Also import your jdbc driver to the project as well us in the Connection.java file

How does Dapper execute query without explicitly opening connection?

We are using Dapper for some data access activity and are using the standard recommended approach for connecting to database as follows:
public static Func<DbConnection> ConnectionFactory = () => new SqlConnection(ConnectionString);
However, if we try and execute a statement, in the docs it show that you need to first state:
using (var conn = ConnectionFactory())
{
conn.Open();
var result = await conn.ExecuteAsync(sql, p, commandType: CommandType.StoredProcedure);
return result;
}
That means, you have to explicitly open the connection. However, if we leave out the statement conn.open(), it also works and we are worried if in such cases the connection may not be disposed of properly.
I would appreciate any comments as to how the SQL gets executed without explicitly opening any connection.
Dapper provide two ways to handle connection.
First is - Allow Dapper to handle it.
Here, you do not need to open the connection before sending it to Dapper. If input connection is not in Open state, Dapper will open it - Dapper will do the actions - Dapper will close the connection.
This will just close the connection. Open/Close is different than Dispose. So, if you really want to Dispose the connection better switch to second way.
Second is - Handle all yourself.
Here, you should explicitly create, open, close and dispose the connection yourself.
Please refer to following links for more details:
https://stackoverflow.com/a/51138718/5779732
https://stackoverflow.com/a/41054369/5779732
https://stackoverflow.com/a/40827671/5779732

How to get rid of "The connection was not closed. The connection's current state is open." error? [duplicate]

I'm writing an ASP.NET application. In my datalayer an sql connection is being opened and closed before and after querying. The SqlConnection is being kept as a private field of a single class. Every database call in the class uses the same structure:
conn.Open();
try
{
// database querying here
}
finally
{
conn.Close();
}
Yet, on very rare occasions I get the exception 'The connection was not closed. The connection's current state is open'. It's not possible to reproduce the problem since it originates very rarely from different parts of the code. There is some threading involved in my application but new threads also make new data layer classes and thus new connection objects.
I do not understand how it's possible to have a connection lingering around open using the code above. Shouldn't the connection always be closed after opening, making it impossible for the above exception to occur?
It's likely that an exception is being thrown in the try block that you aren't handling. See this note in MSDN for try-finally:
Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered.
I would recommend wrapping the connection in a using block anyway:
using (SqlConnection connection = new SqlConnection(connectionString))
{
//etc...
}
Alternatively, add a catch block to the try-finally:
conn.Open();
try
{
}
catch
{
}
finally
{
conn.Close();
}
you should close connections as soon as you operations finished. Try to open connections for the shortest time possible.
However it is best to use using it will call Dispose method even in case of exceptions.
using (SqlConnection conn= new SqlConnection(conStr))
{
//etc...
}
OR
1) Open the connection
2) Access the database
3) Close the connection
//conn.Open();
try
{
conn.Open();
//Your Code
}
finally
{
conn.Close();
conn.Dispose();//Do not call this if you want to reuse the connection
}

ORMLite OpenDbConnection gives AccessViolationException

I am using ServiceStack and OrmLite.Oracle. I connect to an old Oracle 7.3 instance using ODBC Driver for Oracle on a Windows Server 2012 x64. ODBC is setup as an ODBC32.
I connect and query the database from my repo like this:
using (IDbConnection db = _context.DbFactory.OpenDbConnection())
{
return db.Select<T>();
}
The _context hold the OrmLiteConnectionFactory which was created like this:
DbFactory= new OrmLiteConnectionFactory(conInfo.ConnectionString,false, ServiceStack.OrmLite.Oracle.OracleDialect.Provider);
My service is running just fine and I can access and query the database, no problem.
But after a certain period of time (30 minutes or so), the connection is lost and I have to restart my service (hosted in a Windows Service) because the call to Open the connection will give me this error: unable to allocate an environment handle.
It might be a normal thing to release the handle to the connection after a while but why it simply doesn't reconnect to it? From OrmLite code, I can see that OpenDbConnection should return a new instance of its connection when the AutoDisposeConnection is set to True or if the internal ormLiteConnection is null. I guess my connection is not null but not quite alive...
private OrmLiteConnection ormLiteConnection;
private OrmLiteConnection OrmLiteConnection
{
get
{
if (ormLiteConnection == null)
{
ormLiteConnection = new OrmLiteConnection(this);
}
return ormLiteConnection;
}
}
public IDbConnection OpenDbConnection()
{
var connection = CreateDbConnection();
connection.Open();
return connection;
}
public IDbConnection CreateDbConnection()
{
if (this.ConnectionString == null)
throw new ArgumentNullException("ConnectionString", "ConnectionString must be set");
var connection = AutoDisposeConnection
? new OrmLiteConnection(this)
: OrmLiteConnection;
return connection;
}
I have tried to set the AutoDisposeConnection to True but when I do, I always get an AccessViolationException saying "Attempted to read or write protected memory. This is often an indication that other memory is corrupt.". What does that mean? Is this an OS, ODBC or OrmLite error? Any idea why this is happening?
I have to say that because I am using Oracle 7.3, I had to recompile the ServiceStack.OrmLite.Oracle.dll so it uses the System.Data.Odbc rather than System.Data.OracleClient (only compatible with v8+).
I really want to avoid to test if the connection is alive or not at every call, so any help to make this work is greatly appreciated. Thanks

SQLserver2005 connectivty with VC++(code)

I have developed a simple application in Visual studio 2008.Its a combination of C and C++.Now am trying to connect to SQLserver2005.Installed SQlserver2005 managementExpress studio.
Created database and table.To know about the connectivty took a example to insert the data from C code.But its doesnot showing any thing.I know its very simple.But some where am doing wrong.
I would like to clarify few things about the below code.want to do the connectivty locally not server part by using SQLserver2005.
In connection string what username and password i should mention.
what does this line really do."hr = pConn->Open(strCon,"keerth","keerth",0);"
ususally in MYSQL we will create the DNS.but how to mention DNS in SQL server2005.
If i want to insert the variable value(which will display in console window) into database.kindly let me know is it possible? if so suggest me any idea to implement it.
Is there any tutorial links to learn about these things.
#include "stdafx.h"
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
int main(int argc, char* argv[])
{
/*The following variables will be initialized with necessary values and appended to the strSQL values*/
_bstr_t strName;
_bstr_t strAge;
_bstr_t strDOB;
_bstr_t strSalary;
_ConnectionPtr pConn = NULL;
// Define string variables for ADO connection
_bstr_t strCon("Provider=SQLOLEDB.1;Persist Security Info=False;Username=keerth;Password=keerth;Initial Catalog=keerth516;Data Source=(local);Integrated Security=SSPI;");
HRESULT hr = S_OK;
//Initialize the COM Library
CoInitialize(NULL);
try
{
//Create the Connection pointer
hr = pConn.CreateInstance((__uuidof(Connection)));
if(FAILED(hr))
{
printf("Error instantiating Connection object\n");
goto cleanup;
}
//Open the SQL Server connection
hr = pConn->Open(strCon,"keerth","keerth",0);
if(FAILED(hr))
{
printf("Error Opening Database object using ADO _ConnectionPtr \n");
goto cleanup;
}
/*Initialize the values */
strName = "'C++ ADO insert Sample',";
strAge = "23,";
strDOB = "'13/04/1988',";
strSalary = "16600.10)";
/* Append the values to the Insert Statement */
_bstr_t strSQL("Insert into Table1(NAME,AGE,DOB,SALARY) Values(");
strSQL += strName + strAge + strDOB + strSalary ;
printf("%s\n",(LPCSTR)strSQL);
//Execute the insert statement
pConn->Execute(strSQL,NULL,adExecuteNoRecords);
printf("Data Added Successfully\n",(LPCSTR)strSQL);
//Close the database
pConn->Close();
}
catch(_com_error &ce)
{
//printf("Error:%s\n",ce.ErrorInfo);
printf("Error:%s\n,",(char*)ce.Description());
}
cleanup:
CoUninitialize();
return 0;
}
You might want to take a look at the ADO API at http://msdn.microsoft.com/en-us/library/windows/desktop/ms678086(v=vs.85).aspx.
I don't think it makes sense to provide username/password as parameters to Open and as parameters in the connection string. Setting "Integrated Security=SSPI" activates integrated windows logon, so this even makes your username/password more redundant. The connectionString is documented in the MSDN (link above), the connection string parts that are specific to the DB providers are documented here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681020(v=vs.85).aspx.
"pConn->Open(strCon,"keerth","keerth",0);" opens the connection to the database server.
3.ususally in MYSQL we will create the DNS.but how to mention DNS in SQL server2005.
What do you mean with this?
4.If i want to insert the variable value(which will display in console window) into database.kindly let me know is it possible? if so suggest me any idea to implement it.
You can use ADO RecordSet with AddNew or the Execute function in your sample. Using Execute you might add adCmdText to the last parameter.

Resources