I'm trying to execute a query using C#. The problem is that, despite the fact that I modified the timeout period, it thrown a timeout exception. It is rising the exception after 30 seconds, that is the default value.
using (MySqlConnection conn = new MySqlConnection(connStr))
{
int x = conn.ConnectionTimeout;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "SELECT AVG(v.value_min) AS minValue FROM values v";
adpter.SelectCommand = cmd;
adpter.Fill(dados);
conn.Close();
}
As you can see, I'm using conn.ConnectionTimeout to check if the timeout is properly configured and, yes it is. At least it shows the amount of time that I configured (in that case 90).
So, how do I do this? How to run a long time query?
UPDATE: The query that I posted is just an example.
Setting the CommandTimeout property on your MySqlCommand instead of the connection should do the trick.
Related
I have a server that executing SQL queries against Azure SQL Server using ADO.NET
When I'm trying to run a specific query by my server (using ADO.NET) I get a timeout error, but when I'm executing the same query by SQL Server, I get results after 1-2 seconds.
I tried to increase to timeout in the connection string and in the SqlCommand object with no results.
I saw one potential solution to change the timeout in the SqlCommand object to 0, I tried and got results after a long time, but it works only on my local machine and not on my production server
This is the code I'm using in my server to integrate my DB:
using (var connection = new SqlConnection(ConnectionString))
{
var command = new SqlCommand
{
CommandText = query
};
foreach ( var parameter in parameters)
command.Parameters.AddWithValue(parameter.Key, parameter.Value ?? Convert.DBNull);
command.Connection = connection;
try
{
_logger.Info("Open connection to db");
connection.Open();
_logger.Info("Execute command");
SqlDataReader reader = command.ExecuteReader();
List<Column> columns = CreateColumnList(reader);
}
catch (Exception e)
{
_logger.Error(e);
}
}
This is the exception message I get:
The timeout to perform has expired. The timeout period passed before completing the action or the server is not responding
Instead of AddWithValue, specify the actual column database type and max length. For example:
command.Parameters.Add(parameter.Key, SqlDbType.VarChar, 30).Value = parameter.Value ?? Convert.DBNull);
This practice will ensure the parameter type and length matches that of the underlying column and facilitate efficient index use by the query. A big problem with AddWithValue is that it will infer data type nvarchar with strings, which will prevent a SARGable expression against an varchar column with a SQL collation.
The reason the SSMS query runs fast is likely because the ad-hoc query specifies a varchar literal or variable.
I have a local MS SQL Database, and I want to update one of it's bit field.
I have the following code:
static void UpgradeVevo(string nev)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=True Where Nev=" + nev, connection);
command.ExecuteNonQuery();
}
Console.WriteLine(nev+" mostmár törzsvendég");
}
Torzsvendeg is a bit datatype(I have tried to set its value to 1 too), and Nev is varchar.
The connectionstring should be fine, since I have tried Select in another method and it works fine. The above code throws no exceptions, but the table does not get updated.
I have tried to find an answer for quite some time, with no success :/. Thank you for your help in advance!
True should be in a single quote since it's a string literal like
UPDATE Vevok SET Torzsvendeg='True'
Well brother, you are messed up with quotes. Your query should look like
"UPDATE Vevok SET Torzsvendeg = 1 Where Nev = '" + nev + "'"
Again, use parametarized query and not this concatenated one to avoid SQL Injection
If the column is a boolean (bit in sql server) then you will have to write
Torzsvendeg=1
instead of
Torzsvendeg='True'
or
Torzsvendeg=True
Edit:
Please try this:
static void UpgradeVevo(string nev)
{
var connection = new SqlConnection(connectionString))
connection.Open(); // try doing this without a using
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=#enabled Where Nev=#nev", connection);
command.Parameters.AddWithValue(#"enabled", 1);
command.Parameters.AddWithValue(#"nev", "vevo123");
command.ExecuteNonQuery();
command.Parameters.Clear(); // always clear after executed
// close connection when you shut down your application
connection.Close();
connection.Dispose();
Console.WriteLine(nev+" mostmár törzsvendég");
}
Getting a weird exception from ExecuteScalar() that I cannot find any help for on the web:
Cannot continue the execution because the session is in the kill state.
I'm using SqlConnection/SqlCommand
The command is a basic INSERT INTO... with 105 columns (and 105 parameters to set the column data) followed by a SELECT SCOPE_IDENTITY();
I've checked the connection string - it is correct and the connection is open.
I'm not even sure what this error is telling me to know where to start looking on this one.
So what exactly does this error mean? How does a session get in the kill state to begin with?
Code is pretty straight forward:
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO VendorNote (VendorId, AdminComment...) VALUES (#VendorId, #AdminComment, ...); SELECT SCOPE_IDENTITY(); ", conn))
{
cmd.Parameters.AddWithValue("#VendorId", VendorId);
cmd.Parameters.AddWithValue("#AdminComment", AdminComment);
Id = (int) cmd.ExecuteScalar();
}
}
FOUND IT!
There was a constraint violation in the query that was causing execution of the query to fail. Instead of reporting that info in the exception - it was reporting that the session was in a "kill state" (I'm guessing ) because the query was terminated prematurely.
I've never seen this error before - normally constraint errors and such have something more useful in the exception.
So anybody getting this error - REALLY check over your query to make sure it's valid.
Your code should look like this:
const string sqlString = "INSERT INTO dbo.Table ( ....) " +
" VALUES ( .... );" +
"SELECT SCOPE_IDENTITY();";
using (conn)
{
using (var cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.AddWithValue("#param", param);
cmd.CommandType = CommandType.Text;
conn.Open();
return (int) (decimal) cmd.ExecuteScalar();
}
}
But note sometime a stored procedure will be more appropriate
It could be due to an Always On Availability Group 'Failover'...
Whenever I have a running query, connected to an AG Listener, and there is a failover, I get an SqlException having the Message of 'Cannot continue the execution because the session is in the kill state.'...
I am setting CommandTimeout to 1 second and no TimeoutException is being thrown as expected. The query I am running takes about 7-8 seconds. The timeout does work however when I use ExecuteReader to execute a query rather than trying to fill a DataTable. I have tried setting CommandTimeout when after creating the command and also after creating the DataAdapter.
using(SqlConnection con = new SqlConnection("data source=*****;user id==*****;password==*****;initial catalog==*****;"))
{
string query = "select * from *****";
SqlCommand command = new SqlCommand(query, con);
//command.CommandTimeout = 1;
CostingDataSet cds = new CostingDataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
da.SelectCommand.CommandTimeout = 1;
Stopwatch stopwatch = Stopwatch.StartNew();
da.Fill(cds.CostingData);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
The cause is the magic that occurs in the SQLDataAdapter, which is frankly, why they are a bad idea.
My guess is they are using async to perform the fill, which will always ignore command timeouts.
My suggestion: run away from the adapter, and never look back. They aren't that valuable and make everything messier.
If that isn't possible, set your connection timeout in your connection string and it should apply regardless of how the db is accessed.
Queries like "select * from" are a bad idea.
What is the reason not to use select *?
That said, maybe you could restric the amount of data to return, by paging or similar way. Reducing the amount of returned data will make it work
The following code results in a System.Data.SqlClient.SqlException: Timeout expired.
const string sqlStmt = #"SELECT *
FROM CUSTOMER_INFO
WHERE CUSTOMER_NO = #CUSTOMER_NO;";
SqlCommand command = new SqlCommand(sqlStmt, connection);
command.Parameters.AddWithValue("#CUSTOMER_NO", txtAccountNo.Text.Trim().ToUpper());
but this does not time out...
const string sqlStmt = #"SELECT *
FROM CUSTOMER_INFO
WHERE CUSTOMER_NO = #CUSTOMER_NO;";
SqlCommand command = new SqlCommand(sqlStmt, connection);
command.Parameters.Add("#CUSTOMER_NO", SqlDbType.VarChar, 25).Value = txtAccountNo.Text.Trim().ToUpper();
I don't understand why, can anyone enlighten me?
Can you get a look at the SQL statement that gets executed by the database ?
You'll probably see a difference in the type that is used by the parameter. I believe that the AddParamWithValue method will not use the correct type for the parameter.
Then, it is possible that the DBMS will have to convert the value back to the correct type. Some DBMS'es will not be able to use an index-lookup in that case, which will result in a longer running query, hence the timeout.