public partial class Variables_input : System.Web.UI.Page
{
public string conStr = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
protected void Buttonsubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(conStr))
{
try
{
con.Open();
Response.Write("<script language ='javascript'>alert('Connection is open');</script>");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Response.Write("<script language ='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
Response.Write("<script language ='javascript'>alert('Connection is close');</script>");
}
}
}
I am not able to connect to connect my SQL Server database. After running this code I receive "Connection Problem". Please help.
I don't know where to begin to start.
You are using SQL server not mySQL right, you have funny wording. Just want to make sure.
You might want to try looking at the exception data, usually it gives you an error message. You caught the error now read it.
If the error message is not helpful you could put a breakpoint at con.Open() and step into an make sure all the parameters are correct or see where the problem is if the exception error doesn't help.
Might also want to look at this:
dot net pearl for sqlconnection
Related
This question already has answers here:
WinForms app seems "Not Responding" while fetching data from database?
(3 answers)
Closed 4 years ago.
Every time when i open my program, it's say "Not Responding".
though on my form event load only retrieve data from database.
private void form1_Load(object sender, EventArgs e)
{
//LoadDb_1()
//LoadDb_2()
//LoadDb_3()
}
i have tried to put the load database in the form1_shown event, but it's not working either.
how do i overcome this ?, i don't want to wait a several minutes to use the program.
PS: i have no idea how to use thread or async
UPDATE
example inside LoadDb_1()
public void LoadDb_1()
{
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
Datatable dt_main = new Datatable();
try
{
dt_main.Clear();
myConnection.Open();
command.Connection = myConnection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "General.SP_Car";
adapter.SelectCommand = command;
adapter.Fill(dt_main);
gridControl1.DataSource = dt_main;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
You have blocking action, blocking the main thread, this is why your application in not responding, to fix this depends how you are connecting to the database, EF6 or EFCore, basic, dapper....
As you say, you don't know async programming or multithreading, one way to do it, connect to the database when you need, for example on some click, you then connect to the database, get the data and then shut the connection down, the application will not be responding for a few seconds, but that's one way...
You have one big problem in your application as i say, not just not responding windows, you connection is always open, you shouldn't do that, you are making your app and your server vulnerable
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection("your connection string....");
try
{
cnn.Open();
SqlCommand myCommand = new SqlCommand("SQL query....", cnn);
SqlDataReader reader = myCommand.ExecuteReader();
while(reader.Read())
{
// Access the columns by reader["columnName"]
}
// Don't forget to close the connection
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
Useful links:
Learn more about native c# to sql connection : https://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Use sqlconnection with winForms: http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm
Connection strings: https://www.connectionstrings.com/
Check on youtube for Tim Corey (https://www.youtube.com/user/IAmTimCorey) , he has great c# tutorials for Threading, async/await, dapper, ASP.NET and much more
I'm trying to make a program with a login system
I'm new to this but I have been working 8 hours straight trying to fix this.
This is the error code I get
+ ServerVersion 'con.ServerVersion' threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException}
Here's my code
private void LogB_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=Myip;user id=MyId;database=MyDb;password=MyPw;persistsecurityinfo=True");
SqlDataAdapter sda = new SqlDataAdapter("Select * From login where navn='"+ TULog.Text + "' and pw='" + TPLog.Text + "'",con);
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
throw ex;
}
finally
{
con.Close();
}
}
}
}
Sorry If this seems like some crap but I'm a guy who's trying to learn :p
This exception is telling you that there was an attempt to access the con.ServerVersion property while the SqlConnection was closed.
From MSDN on the SqlConnection.ServerVersion property:
InvalidOperationException - The connection is closed. ServerVersion was called while the returned Task was not completed and the connection was not opened after a call to OpenAsync.
The code you show above does not show a call to this property, you must be doing so somewhere else. Regardless, the connection needs to be open prior to doing so.
I have a (Windows Forms) app that will be installed on various users' desktops; it will allow them to generate reports based on custom code that connects to a SQL Server Database and reads records from certain tables.
The Connection String is:
Data Source=PLATYPUS;Initial Catalog=Duckbills;Persist Security Info=True;User ID=lilabner;Password=d0GpAtCh42;Connect Timeout=120
I understand this to mean that if all the following is true:
The user's machine has the SQL Server client software installed
The SQL Server client has been configured to access the PLATYPUS database
The table "Duckbills" exists in that database
The username and password are what is expected
...then the connection will be successful.
In the event any of the above equate to false, I want to show the user a "user-friendly" message informing them, in plain English, what the problem is and what to do about it. How can I test for these various problems so that the most appropriate message is shown the user in the event of connection failure.
Here is the pertinent existing code:
DataSet dsUsage = new DataSet();
SqlConnection conn =
new SqlConnection("SERVER=PLATYPUS;DATABASE=Duckbills;UID=lilabner;PWD=d0GpAtCh42;Connection Timeout=0");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "Exec sp_ViewPlatypi";
da.SelectCommand = cmd;
conn.Open();
da.Fill(dsUsage);
conn.Close();
DataTable dtUsage = dsUsage.Tables[0];
if (dtUsage.Rows.Count > 0)
{
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
catch (Exception ex)
{
String exDetail = String.Format(PlatypusConstsAndUtils.ExceptionFormatString, ex.Message, Environment.NewLine, ex.Source, ex.StackTrace);
MessageBox.Show(exDetail);
}
As you can see, I have a "catch all" (no pun intended) Catch block. I want something like:
catch (SQLServerException sex)
{
MessageBox.Show("SQL Server not available - go tell the DBA");
}
catch (NoTableException ntex)
{
MessageBox.Show("Go tell the DBA there's no such table");
}
catch (BadPwdException sex)
{
MessageBox.Show("Your username and/or password are bad - go tell it to the Marines");
}
catch (Exception ex)
{
String exDetail = String.Format(PlatypusConstsAndUtils.ExceptionFormatString, ex.Message, Environment.NewLine, ex.Source, ex.StackTrace);
MessageBox.Show(exDetail);
}
...but I don't know, first if all, if it's even possible to get that granular with connection exception messages, and secondly - if it is - just what the corresponding Exception types are.
Strip your code back to handle Exception (catch (Exception ex)). Then, put a break point in your catch block. Attach the debugger to your code and when it hits the catch block, drag the ex variable in to your watch window. There, you will see all the details of the exception and you can determine what you need to be able to better handle the various exceptions that come up.
Based on MethodMan's suggestion and TheShaman's link, I adapted that code to this:
catch (SqlException sex)
{
for (int i = 0; i < sex.Errors.Count; i++)
{
String sexDetail = String.Format("SQL Exception #{0}{1}Source: {2}{1}Number: {3}{1}State: {4}{1}Class: {5}{1}Server: {6}{1}Message: {7}{1}Procedure: {8}{1}LineNumber: {9}",
i+1, // Users would get the fantods if they saw #0
Environment.NewLine,
sex.Errors[i].Source,
sex.Errors[i].Number,
sex.Errors[i].State,
sex.Errors[i].Class,
sex.Errors[i].Server,
sex.Errors[i].Message,
sex.Errors[i].Procedure,
sex.Errors[i].LineNumber);
MessageBox.Show(sexDetail);
}
}
catch (Exception ex)
{
String exDetail = String.Format(UsageRptConstsAndUtils.ExceptionFormatString, ex.Message, Environment.NewLine, ex.Source, ex.StackTrace);
MessageBox.Show(exDetail);
}
And for an example of what this produces:
I'd like my code to give a warning or something whenever the database is not available.
(That's why I commented the connection string), but my website just crashes.
I created this class cause there were many parts of the program using this connection string (login page, register page, user panel page, etc), so if I want to change something in the future, this is the only string I have to change.
namespace Fatture.Data.User
{
public class DbConnection
{
public MySqlConnection ConnessioneDb()
{
MySqlConnection conn = new MySqlConnection(/*ConfigurationManager.ConnectionStrings["ConnectionStringloginDb"].ConnectionString*/);
try
{
conn.Open();
}
catch (Exception ex)
{
throw new Exception("I can't connect to the database", ex);
}
return conn;
}
}
}
Use exception handling...
var connector = new DbConnection();
try
{
var connection = connector.ConnessioneDb();
}
catch (Exception ex)
{
// show message to user: database not available
}
Though you'll have to put this in place everywhere you access the database. Instead you can also just set up error handling for your entire site.
Catch the exception...
try
{
var conn = new DbConnection().ConnessioneDb();
}
catch (Exception ex)
{
// Notify user here
}
I built a parser that takes data stored in an xml file and sends it into a Microsoft Access database using linq-to-sql. I have the sql insert commands and they work... until they don't.
It's odd, I have each SQL command run (I keep them in a List and execute each command one at a time) and the first 40 or so run fine until they start hitting "unspecified error"s. The thing is, if I swallow the exception and instead have the exception catcher keep retrying, after a few seconds, they start working again. This means it's not an error of the SQL query itself (or at least how it's written).
This pattern repeats (there are thousands of inserts) many times. If I do normal exception handling, the program will just skip a few records while the error happens and keep inserting when whatever causes it temporarily goes away. if I let it run it's course, it inserts some records, skips some, inserts, skips, repeat and eventually inserts less than 2/3 of the records.
Is there any reason why my computer would only run 40 or so Inserts and then refuse to run more for a random but short interval?
I'm at a loss on what could be causing this.
The application is natively run; it does not use any server/web communication and all I found when looking for "unspecified error" pointed me to occurrences in ADO.NET applications.
Here's the code the error happens in:
public static string insertQuery(string sql)
{
string connetionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Owner\Desktop\Arbeit\TrademarkParserproject1\TrademarkParserproject\bin\x86\Debug\Database.accdb";
OleDbConnection connection;
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
connection = new OleDbConnection(connetionString);
string success = "false";
try
{
connection.Open();
oledbAdapter.InsertCommand = new OleDbCommand(sql, connection);
oledbAdapter.InsertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
success = ex.ToString();
return success;
}
success = "true";
return success;
}
Note, I have the application running in X86 mode to avoid errors with the ACE.OLEDB.12.0 adapter.
One thing that stands out, is you never close/dispose your SqlConnection. OleDbDataAdapter is also disposable and should be disposed. A 'using' statement is a convenient construct here:
public static string insertQuery(string sql)
{
string connetionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Owner\Desktop\Arbeit\TrademarkParserproject1\TrademarkParserproject\bin\x86\Debug\Database.accdb";
using(var oledbAdapter = new OleDbDataAdapter())
using(var connection = new OleDbConnection(connetionString))
{
string success = "false";
try
{
connection.Open();
oledbAdapter.InsertCommand = new OleDbCommand(sql, connection);
oledbAdapter.InsertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
success = ex.ToString();
return success;
}
success = "true";
return success;
}
}