Catch SqlException

D

Dan Pavel

Hi,

I have a webform where the user can enter a database server, a database,
a user, a password and an SQL string and run it. The result is displayed
in a textbox. My problem is when the user enter non existing server name
or non existing database, the SqlException i receive in catch is "SQL
Server does not exist or access denied" even if the database name is
wrong. Is there any way to receive these exceptions like "Database does
not exist or access denied" or something like that ?

try
{
con = new SqlConnection("server="+TextBox3.Text+";User
ID="+UsernameTxt.Text+";Password="+PasswordTxt.Text+";database="+TextBox
4.Text+";Connect Timeout=30");
cmd = new SqlCommand(TextBox1.Text, con);
con.Open();
rd = cmd.ExecuteReader();
while (rd.Read())
{
for (int i=0;i<rd.FieldCount;i++)
TextBox2.Text+=rd.GetValue(i)+" ";
TextBox2.Text+="\n";
}
con.Close();
}
catch (SqlException ex)
{
Response.Write("<script>javascript:window.open('popup.aspx?Type=1&Mes="+
ex.Message+"','','width=250,height=150,resizable=no,status=no,toolbar=no
')</script>");
}

Thank you,
Dan
 
N

Nicholas Paldino [.NET/C# MVP]

Dan,

You can get around this specifically by testing the database server, and
then the database names before you try and connect (through various APIs).

Instead of this though, why not just offer a drop down list of all the
database servers, and then the databases in each server (when a server is
picked), so that you can limit the chance that an erroneous server is
chosen?

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top