I have come across a tricky little problem and here and it is to do with opening a SQL Server database
The calling code is
public MainWindow()
{
InitializeComponent();
dbTools = new DataBaseTools();
if (dbTools.DbWorks)
{
label3.Text = "Worked";
}
else
{
label3.Text = "Try Again";
}
label3.AutoSize = true;
}
and the code for connecting to the server is
namespace LeatherCorset
{
public class DataBaseTools
{
private Boolean dbWorks;
private SqlConnection myConn;
public DataBaseTools(){
dbWorks = false;
InitialiseDatabase();
}
private void InitialiseDatabase(){
myConn = new SqlConnection();
String ConnString =
"Server=KEITH\\SQLEXPRESS;Database=Corset;Trusted_Connection=Yes";
myConn.ConnectionString = ConnString;
try{
if (myConn.State == ConnectionState.Open){
dbWorks = true;
}
}catch (SqlException ex) {
dbWorks = false;
}
}
public Boolean DbWorks{
get { return dbWorks; }
set { dbWorks = value; }
}
}
}
When I run the debugger it comes up with connString with having the value of null.
The name of the server is DESKTOP\SQLEXPRESS
The name of the database is Corset
The owner is Desktop\Keith
I am lost at this point in how to get to connect to SQL Server from c#
I would appreciate any advice and help
I don't see where you have opened the connection using Open(). Also, it is better practice here to initialize the SqlConnection with the correct string. Try something like
bool dbWorks = false;
sting cs = "Data Source=KIETH\\SQLEXPRESS;Initial Catalog=Corsit;Trusted_Connection=Yes";
using (SqlConnection conn = new SqlConnection(cs))
{
try
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
dbWorks = true;
}
}
}
I hope this helps.
Can't see how ConnString is null, I think you may be having some debugging issues, that said, try this:
String ConnString = "Server=KEITH\\SQLEXPRESS;Database=Corset;Trusted_Connection=Yes";
using (myConn = new SqlConnection(ConnString)) // This will make sure you actually close the DB
{
myConn.Open(); // You need to open the connection
try
{
if (myConn.State == ConnectionState.Open)
{
dbWorks = true;
}
}
catch (SqlException ex)
{
dbWorks = false;
}
}
I'd also recommend actually taking out the try/catch, because you're hiding an exception that may tell you everything that's going wrong.
Related
I would like to add some information to my database. I searched for some tutorials, but none of them work.
NonQuery can do what he needs to do, because the messagebox returns "Success" (1). But it does not update my database. If I put the same query to "Add New Query", directly to my database, it works.
Can someone help me?
My class code at the moment:
namespace BurnThatFat
{
class databaseconnection
{
//fields
SqlConnection connection;
string connectionstring;
public databaseconnection()
{
// fields waarde toewijzen
connectionstring = #"Data Source=(LocalDB)\MSSQLLocalDB;" +
#"AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
connection = new SqlConnection(connectionstring);
OpenConnection();
CloseConnection();
}
public List<Object> getObjectsFromDatabase()
{
try
{
OpenConnection();
// sql query
// Datareader
// sqlcommand
// return list van objecten , objecten veranderd naar jouw wens van data.
CloseConnection();
}
catch (Exception)
{
throw;
}
return new List<object>();
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (connection)
{
SqlCommand command = new SqlCommand(query, connection);
OpenConnection();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
}
Edit:
And this is the code for my buttons etc:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// voor sql connectie.
using System.Data.SqlClient;
namespace BurnThatFat
{
public partial class SignUp : Form
{
databaseconnection db = new databaseconnection();
public SignUp()
{
InitializeComponent();
gb_login.Visible = false;
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = false;
gb_email.Visible = false;
gb_Start.Visible = true;
}
private void btn_SignUp_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_Voornaam.Visible = true;
}
private void btn_login_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_login.Visible = true;
}
private void btn_loginvolgende_Click(object sender, EventArgs e)
{
gb_login.Visible = false;
// hier moet nog een GB!!!!!!
}
private void btn_voornaamvolgende_Click(object sender, EventArgs e)
{
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = true;
}
private void btn_achternaamvolgende_Click(object sender, EventArgs e)
{
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = true;
}
private void btn_leeftijdvolgende_Click(object sender, EventArgs e)
{
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = true;
}
// einde registratie
// opslaan van gegevens in database
private void btn_emailvolgende_Click(object sender, EventArgs e)
{
// gebruiker = new Gebruikerklasse();
// gebruiker.Naam = Convert.ToString(tb_voornaam.Text);
//// gebruiker.Achternaam = Convert.ToString(tb_achternaam.Text);
// gebruiker.Leeftijd = Convert.ToInt32(nud_leeftijd.Value);
/// gebruiker.Geslacht = Convert.ToString(cb_geslacht.Text);
// gebruiker.Huidig_gewicht = Convert.ToInt32(nud_huidiggewicht.Value);
// gebruiker.Streef_gewicht = Convert.ToInt32(nud_streefgewicht.Value);
/// gebruiker.Gebruikersnaam = Convert.ToString(tb_gebruikersnaam2.Text);
// gebruiker.Email = Convert.ToString(tb_email.Text);
// gebruiker.Wachtwoord = Convert.ToString(tb_wachtwoordsignup.Text);
db.AddGebruiker();
gb_email.Visible = false;
// hier moet nog een GB!!!!!
}
private void btn_gewichtvolgende_Click(object sender, EventArgs e)
{
gb_gewicht.Visible = false;
gb_email.Visible = true;
}
}
}
The simplest way to insert into a SQL Server database:
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
string commandText = "INSERT INTO MyTable (ID, Name, Address) VALUES (10, 'Bob', '123 Main Street');";
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
As long as commandText is a working query, it should insert a row. It would be better to use parameters for your values instead of hard coding them like I did here - that avoids SQL injection attacks and other potential problems. You can search Google for that (or the question you are asking now) and find tons of resources to help you.
If you need more specific help, post details such as what is actually happening when you try to run your code - are you getting an exception?
I'd clean up a bunch of things before doing anything else.
First, get rid of the openconnection and closeconnection methods all together. And don't keep an instance property for the connection in your class. Create the connection ondemand with a using statement, because at the end of the using statement the compiler will insert a call to the Dispose method on the connection's IDisposable interface implementation and it will close the connection automatically for you.
So after cleaning up all the unnecessary code all you really should have in this class is an implementation of your Addgebrukier method which would look like this
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
You should also load your connection string from the section in the app/web.config, but you can do that later after you get it running.
Here is a simple concept that should work perfectly fine for you. Just change the ServerName, DatabaseName, etc.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
My class has a couple of methods going on. The first one is creating a database, that's done. Then, creates stored procedures that is being read from a sql file. then detach that DB. Now it seems that my store procedure query is taking a while to finish and my method to detach is being invoked while the database is busy. So how do I tell if the database is idle. The exception goes "cannot detach the database because it is currently in use"
Methods:
void CreateStoredProcedures(string type)
{
string spLocation = File.ReadAllText("CreateStoredProcedures.sql");
var conn = new SqlConnection(connectionString + ";database=" + type + DateTime.Now.ToString("yyyyMMdd"));
try
{
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(spLocation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
bool DetachBackup(string type)
{
var conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("", conn);
command.CommandText = #"sys.sp_detach_db '" + type + DateTime.Now.ToString("yyyyMMdd") + "'";
try
{
conn.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
return true;
}
Click event:
private void btnFullBackup_Click(object sender, EventArgs e)
{
lblStatus.Text = "Starting full backup...";
Execute("FULL");
progressBar.Value = 20;
lblStatus.Text = "Copying tables...";
progressBar.Value = 60;
CopyTables("FULL");
progressBar.Value = 70;
lblStatus.Text = "Creating stored procedures...";
CreateStoredProcedures("FULL");
progressBar.Value = 80;
CheckDBSize(newBackupLocation, "FULL");
progressBar.Value = 100;
MessageBox.Show("Backup was created successfully", "",
MessageBoxButtons.OK, MessageBoxIcon.Information);
lblStatus.Text = "Done";
progressBar.Value = 0;
if (DetachBackup("FULL") == false)
{
DetachBackup("FULL");
}
}
Chances are it's getting hung on its own connection. sp_detach_db's MSDN https://msdn.microsoft.com/en-CA/library/ms188031.aspx has the following suggestion under the section Obtain Exclusive Access:
USE master;
ALTER DATABASE [DBName] SET SINGLE_USER;
You're DetachBackup method will have connect to master, run the ALTER and the sp_detach_db procedure.
You aren't closing the connection in your CreateStoredProcedures method. Put using statements in like I've shown here and it should fix the problem. (Brief using statement explanation from Microsoft.)
Try this code for your methods:
void CreateStoredProcedures(string type)
{
string spLocation = File.ReadAllText("CreateStoredProcedures.sql");
using (var conn = new SqlConnection(connectionString + ";database=" + type + DateTime.Now.ToString("yyyyMMdd")))
{
try
{
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(spLocation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
} // End of using, connection will always close when you reach this point.
}
bool DetachBackup(string type)
{
using (var conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(#"sys.sp_detach_db '" + type + DateTime.Now.ToString("yyyyMMdd") + "'", conn);
try
{
conn.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
} // End of using, connection will always close when you reach this point.
return true;
}
You shouldn't think of it as the database being "busy", but the error message uses good verbage: in use. To find out if the database is currently in use, the most accurate way would be to find out if any sessions have any lock in the particular database, by querying sys.dm_tran_locks. Here is a helper function to return a bool whether or not the database is in use:
bool IsDatabaseInUse(string databaseName)
{
using (SqlConnection sqlConnection = new SqlConnection("... your connection string ..."))
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConnection;
sqlCmd.CommandText =
#"select count(*)
from sys.dm_tran_locks
where resource_database_id = db_id(#database_name);";
sqlCmd.Parameters.Add(new SqlParameter("#database_name", SqlDbType.NVarChar, 128)
{
Value = databaseName
});
sqlConnection.Open();
int sessionCount = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (sessionCount > 0)
return true;
else
return false;
}
}
Note: Make sure your initial catalog in your connection string isn't the database you're trying to make "not in use", as that'll put your current session in the context of the database, not allowing that operation to complete
We have this class to use like SingleTon to return the same connection and transaction(isolation level read commited)(we use CRUD):
public class SharedDbMySQL : DatabaseMySQL
{
private static DatabaseMySQL sConn;
private SharedDbMySQL()
{
}
public static DatabaseMySQL GetInstance()
{
return GetInstance(TipoDados.Dados);
}
public static DatabaseMySQL GetInstance(TipoDados OpcoesBD)
{
if (sConn == null)
sConn = new DatabaseMySQL(OpcoesBD);
return sConn;
}
}
With the SQL(microsoft)... the error dont occours... only the Mysql.
We insert first the "NotaFiscalEntrada"...
After we insert the products of this "NotaFiscalEntrada" on this method(and we have the error here):
public static void InsereAtualizaNotaFiscalEntradaProduto(List<nf_entrada_produto> entity, int IDNFEntrada, bool SharedConnection, bool LastOperation)
{
DatabaseMySQL db;
MySqlCommand cmd = new MySqlCommand();
if (SharedConnection)
db = SharedDbMySQL.GetInstance();
else
db = new DatabaseMySQL();
try
{
cmd.Connection = db.Conn;
cmd.Transaction = db.BeginTransaction();
ONF_Entrada_Produto OpNFProduto = new ONF_Entrada_Produto(cmd);
foreach (nf_entrada_produto Item in entity)
{
Item.ValorICMSST = 0;
Item.IDNFEntrada = IDNFEntrada;
Item.IDEmpresa = BusinessLogicLayer.ObjetosGlobais.DadosGlobais.EmpresaGlobal.ID;
if (Item.ID == 0)
{
if (!OpNFProduto.Add(Item))
throw OpNFProduto.LastError;
}
else
{
if (!OpNFProduto.Update(Item))
throw OpNFProduto.LastError;
}
}
if (LastOperation || !SharedConnection)
{
db.CommitTransaction();
db.Disconnect();
}
}
catch (Exception ex)
{
db.RollBackTransaction();
db.Disconnect();
throw ex;
}
}
The error is when we insert the Products (code above)
"Lock wait timeout exceeded; try restarting transaction".
We found something about the deadlock... the lost of the connection can be the error, how to resolve it?I think thats a server error? thanks all.
The Problem was on the METHODS... I created again a new connection and not taking it from the singleton...
And the database deadlock the tables and other connections try to change it too... and there is the problems.
cmd.Connection = new db.Connect();
cmd.Connection = db.Conn;
replaced to
cmd.Connection = db.Conn;
Inside of class db(singleton):
MySqlConnection conn;
public MySqlConnection Conn
{
get
{
if ((conn == null) || (conn.State == System.Data.ConnectionState.Closed))
{
Connect();
}
return conn;
}
set
{
conn = value;
}
}
public override void Connect()
{
RetornaDadosIniParaClasse();
conn = new MySqlConnection(StringConnection);
try
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Closed)
{
throw new AccessDatabaseException("Conexão com o banco de dados firebird fechada");
}
}
catch (Exception ex)
{
throw new AccessDatabaseException(ex.Message);
}
}
It taked a lot of time because its difficult to see the error... we debuged it a lot to find it.
Assuming that I call the method below with the right credentials:
private bool Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
bool isConnected = false;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
isConnected = true;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
conn.Close();
}//finally
return isConnected;
}
I have successfully open the connection in my method below:
private bool ValidateUserCode(string usercode)
{
UserAccountDefine def = new UserAccountDefine();
UserAccountService srvc = new UserAccountService();
UserAccountObj obj = new UserAccountObj();
bool returnVal = false;
bool isValid = Connect(def.DB_DUMMY_USERCODE, def.DB_DUMMY_PASSWORD);
if (isValid)
{
obj.SQLQuery = string.Format(def.SQL_LOGIN, usercode.ToLower(), DateTime.Now.ToString("MM/dd/yyy"));
DataTable dt = srvc.Execute(obj, CRUD.READALL);
if (dt.Rows.Count == 1)
{
returnVal = true;
}
}
return returnVal;
}
The question is how can I determine the connection status in ValidateUserCode() method?
How can I close it afterwards?
Note:
I explicitly declare the string variables in UserAccountDefine(); so you don't have to worry about that.
I already tried declaring a new OleDbConnection conn inside the ValidateUserCode() to but the conn.State always returning "Closed".
UPDATE
I have a system with 2-layer security feature. 1st is in application and 2nd is on database. If a user logs in to the application, the username and password is also used to log him/her in to the database. Now, the scenario is when a user forgot his/her password, we can't determine the fullname, email and contact (which are maintained in the database) of the user. I just know his usercode. To determine the contact details, I have to open an active connection using a DUMMY_ACCOUNT.
Note that I never maintain the password inside the database.
First of all, you call Close() in your finally block, which means that at any point in your second method, the connection would be closed. Moreover, even if you don't Close() it,since conn is a local variable in Connect(), when you're back in ValidateUserCode(), the connection is already up for garbage collection, and when it's Dispose()d, it also closes automatically.
I sugges you either make it a member, pass it as an out parameter, return it by the Connect() method (and return null for failure, or something, if you don't like exceptions)..or redesign the code.
private OleDbConnection Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
return conn;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
//you don't want to close it here
//conn.Close();
}//finally
return null;
}
I am not sure how this information helps you.
I had similar problem while using OLEDB connection for Excel Reading. I didn't knew the answer. So, just I added a global variable for OleDbConnection initialized to null.
In my method, I used to check that null, if not close it and again open it.
if (con != null)
{
con.Close();
con.Dispose();
}
try
{
con = new OleDbConnection(connectionString);
}
catch (Exception ex)
{
MessageBox.Show("oledbConnection = " + ex.Message);
}
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show("connection open = " + ex.Message + "\n");
}
I could able to continue after this. You can try, if it works for you its good!
I'm not sure I follow the question quite right. My answer is based on the premise that you want to open/retrieve a connection, take an action, and close/release the connection afterward.
The code you include does not do that well. Typical DAO code resembles this pseudocode, in my case taken from some boilerplate code I use.
public DataSet FetchDataSet(string sql, IDictionary paramHash) {
var cnn = AcquireConnection();
var rtnDS = new DataSet();
try
{
var cmd = cnn.CreateCommand();
cmd.CommandText = sql;
SetParameters(cmd, paramHash);
IDbDataAdapter ida = new DataAdapter { SelectCommand = cmd };
LogSql(sql, paramHash, "FetchDataSet");
ida.Fill(rtnDS);
}
catch (Exception ex)
{
DebugWriteLn("Failed to get a value from the db.", ex);
throw;
}
finally
{
ReleaseConnection(cnn);
}
return rtnDS;
}
Note that the code above is strictly about communicating with the database. There is no assessment of whether the data is right or wrong. You might have a DAO that is a subclass of the one that contains the above code, and it might do this:
public MyItemType FindSomeValue(long Id)
{
const string sql = #"SELECT something from somewhere where id=:id";
var myParams = new Dictionary<string, long> { { "id", Id } };
var ds = FetchDataSet(sql, myParams);
return (from DataRow row in ds.Tables[0].Rows
select new Item
{
Id = Convert.ToInt64(row["ID"], CultureInfo.InvariantCulture),
Name = row["NAME"].ToString()
}).FirstOrDefault();
}
In fact, the above is pseudocode from a DAO implementation that I've used for years. It makes data access relatively painless. Note that there is some real code behind those methods like SetParameters (30 - 80 lines or so), and I have a bunch of other protected methods like FetchScalar, ExecuteSQL, etc.
I have to save data and I have to test connection before to save it. How can I test that this connection string is valid for a particular connection?
My code is like this:
static public bool TestConnString(string connectionString)
{
bool returnVal = true;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
if (conn.State != ConnectionState.Open)
returnVal = false;
else
returnVal = true;
}
catch (Exception ex)
{
returnVal = false;
}
}
return returnVal;
}
Connection string is:
Data Source=testSvr03\SQLEXPRESS;Initial Catalog=Test; Connection Timeout=600; Persist Security Info=True;User ID=Test; password=test
If I give wrong data source in connection String then it never returns in this function after conn.open() .I put catch block but it is coming in it
Can anyone Tell me what is solution?
You can let the SqlConnectionStringBuilder constructor check it:
bool isValidConnectionString = true;
try{
var con = new SqlConnectionStringBuilder("ABC");
}catch(Exception)
{
// can be KeyNotFoundException, FormatException, ArgumentException
isValidConnectionString = false;
}
Here's an overview of the ConnectionStringBuilders for the different data providers:
Provider ConnectionStringBuilder
System.Data.SqlClient System.Data.SqlClient.SqlConnectionStringBuilder
System.Data.OleDb System.Data.OleDb.OleDbConnectionStringBuilder
System.Data.Odbc System.Data.Odbc.OdbcConnectionStringBuilder
System.Data.OracleClient System.Data.OracleClient.OracleConnectionStringBuilder
You can put the return statement just in the catch block like this
static bool TestConnectionString(string connectionString)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
try
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
catch
{
return false;
}
}
return false;
}
I have just tried this. It works correctly (returns false value) if you call this function with empty string.
You can just try to open connection
SqlConnection myConnection = new SqlConnection(myConnString);
try
{
myConnection.Open();
}
catch(SqlException ex)
{
//Failure to open
}
finally
{
myConnection.Dispose();
}
You can do it in background thread
and you can set Timeout, If you don't want waiting long
This is what I ended up using:
private bool validateConnectionString(string connString)
{
try
{
var con = new SqlConnectionStringBuilder(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
}
catch
{
return false;
}
}
Try this. This is the easiest way to check a connection.
try
{
using(var connection = new OleDbConnection(connectionString)) {
connection.Open();
return true;
}
}
catch {
return false;
}
you mean connection string?
well, something like this maybe...
try
{
//....try to connect and save it here, if connection can not be made it will throw an exception
}
catch(Exception ex)
{
}
Create a connection object and try to open it.
An exception will be throw if the connection string is invalid.
Something like this:
using(var connection = New SqlConnection("..."))
{
connection.Open();
}