简体   繁体   中英

How to run application with SQl database in its Form_Load in startup

I have developed an application using C# on Visual Studio 2010 and SQL Server 2008. My application is like a notification program that appears when the windows starts in the Application's start-up Form_Load event it connects to the SQL database as follows

da = new SqlDataAdapter("select info_id,info_text,cat_id from info " + cat, a.GetConnectionStringByName());
SqlCommandBuilder br = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds, "em");
richTextBox1.Text = "";
txt = "";
DataRow dr = GetRow();
if (dr != null)
{
    richTextBox1.Text = dr["info_text"].ToString();
    txt = richTextBox1.Text;
} 

and this is my connection string

<add name="Info_Bank_Project.Properties.Settings.KBankConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\KBank.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> 

When the application run in the startup when the system start, it makes an exception that says that connection timed out Does anyone have an idea about the reason of that exception and how to solve it?

Connection timeout occurs while you attempt to establish a connection to the database and the Database does not respond within 15 seconds (default value).

If you get this sort of problem is because your database server is probably not listening for connections or your connection string is wrong.

I haven't seen a SQL connection string with a .\\SQLEXPRESS as the source. I'm guessing it points to localhost? If you are running this at windows start up are you sure that SQL is up and listening on its port before this app fires off? As Icarus mentions SQL will timeout on you if it takes too long (default 15s) you can change it with the Connection Timeout field in the connection string ( connection string MSDN . A better way in my opinion would be to add some logic before your connection attempt that checks to see if something is listening on the SQL port before continuing on.

The top answer for In C#, how to check if a TCP port is available? shows how to do this in C# it should fairly simple to translate into VB. You'd just put this in a loop that sleeps say for 3s and tries again until the port is being used (so the inverse of this example) for up to 20 times (1 minute) or however long you want before giving up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM