I am wanting to delete all data from a table and reset the id column to 1. I want to do this in my controller, but i want to know the best way to do that. I have tried the SQLConnection/SQLCommand route, but have been unable to connect to the database successfully to do that. Is there a way like running a db.Clean function or something like that?
Updated
Here is how far it gets in the code:
string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Webs\\MvcFFL\\MvcFFL\\App_Data\\Players.mdf;Integrated Security=True";
string queryString = "Truncate table Players;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open(); <- Fails here opening the connection
}
Then when it hits the connection.Open() here is the error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
What can i do instead of this method?
You have an unescaped \in (LocalDB)\v11.0
You can change it to (LocalDB)\\v11.0, or else change the whole connection string to
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Webs\MvcFFL\MvcFFL\App_Data\Players.mdf;Integrated Security=True" (notice the # and the lack of \\)
Related
Description:
I have an application that connects to an Azure Serverless Database. The database can be in a paused state and in an online state. The database auto-pauses when there has been no activity for one hour. This means that when my application tries to open a connection to the database when it is paused, the connection times out and gives a timeout exception.
Azure states in their documentation that:
If a serverless database is paused, then the first login will resume the database and return an error stating that the database is unavailable with error code 40613. Once the database is resumed, the login must be retried to establish connectivity. Database clients with connection retry logic should not need to be modified. source
I am able to get this error code 40613 returned when I try to connect to the database via SQL Management Studio. But when I try to open a connection to the database from my application I only get a timeout exception, hence I don't know whether or not the database is not available or if the database is in fact resuming.
Code example:
public IDbConnection GetConnection()
{
var connection = new SqlConnection(_connectionString);
try
{
connection.Open();
return connection;
}
catch (SqlException e)
{
if (e.Number == 40613)
{
//Database is resuming
}
}
finally
{
connection.Close();
}
}
Exception example:
When I run my application and the database is in paused state I get this exception:
Snippet of exception in Visual Studio
Does anyone know why I don't get the error code 40613 that Azure states in their documentation?
Indeed you may get timeout errors when the Azure database is unavailable. In fact you may get the following errors:
HTTP error GatewayTimeout : The gateway did not receive a response
from ‘Microsoft.Sql’ within the specified time period
HTTP error ServiceUnavailable : The request timed out
SQLException : Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
You may get also error 40613 but you can capture some transient errors like below too:
•Database on server is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of
•Database on server is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of . (Microsoft SQL Server, Error: 40613)
•An existing connection was forcibly closed by the remote host.
•System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
•An connection attempt to a secondary database failed because the database is in the process of reconfguration and it is busy applying new pages while in the middle of an active transation on the primary database.
Because of those errors and more explained here, it is necessary to create a retry logic on applications that connect to Azure SQL Database.
public void HandleTransients()
{
var connStr = "some database";
var _policy = RetryPolicy.Create < SqlAzureTransientErrorDetectionStrategy(
retryCount: 3,
retryInterval: TimeSpan.FromSeconds(5));
using (var conn = new ReliableSqlConnection(connStr, _policy))
{
// Do SQL stuff here.
}
}
More about how to create a retry logic here.
When debugging in SQL, I get the following exception :-
System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'
When I then set next statement and run the statement again, it works. It also works when I'm running the application standalone as a compiled application. Anyone know why this causes an error only when in debug.
The connection is to a remote database sited off-site, not to the local database.
Data Source=xx.xx.xx.xx;Initial Catalog=TheDatabase;User ID=MasterUser;Password=AsIfIMGoingToPostThat
Your help, appreciated.
This is my function to connect...
Public Sub New(ByVal strConnect As String)
Try
dbConnect = New System.Data.SqlClient.SqlConnection(strConnect)
dbConnect.Open()
objParams = New List(Of SqlClient.SqlParameter)
m_bIsConnected = True
Catch exc As Exception
m_bIsConnected = False
Finally
End Try
It looks like your local connection doesn't default to named pipes but your compiled version will try (or is allowed to use TCP/IP). The error shows that it may be expecting named pipes.
Try putting this "np:" in the Data Source in your connection string:
Data Source=np:xx.xx.xx.xx; ...
To get it to connect first time, it looks like I need to add "Network Library=DBMSSOCN;" to connect in debug. t.b.h., Have no idea why...
I have created an ODBC connections (both 32/64 bit) with configuration given below:
Microsoft SQL Server ODBC Driver Version 10.00.14393
Data Source Name: ODBCMSSQL
Data Source Description:
Server: .\SQLEXPRESS
Database: MedicalMarketting
Language: (Default)
Translate Character Data: Yes
Log Long Running Queries: No
Log Driver Statistics: No
Use Regional Settings: No
Prepared Statements Option: Drop temporary procedures on disconnect
Use Failover Server: No
Use ANSI Quoted Identifiers: Yes
Use ANSI Null, Paddings and Warnings: Yes
Data Encryption: No
I want to connect to local MsSQL server as given in below code snippet:
string connectionString = "Data Source=ODBCMSSQL;Initial Catalog=MedicalMarketting;Integrated Security=True";
con = new OdbcConnection(connectionString);
cmd = new OdbcCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
try
{
this.con.Open();
this.tr = con.BeginTransaction();
this.cmd.Transaction = tr;
}
catch (Exception ex)
{
this.RollBack();
}
This throws an exception which has an error message as below:
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Sorry if this was too basic, but had to post for a clue because the same configuration for different ODBC connections works perfectly.
I found a quick fix to the problem by changing the connection string to,
string connectionString = "DSN=ODBCMSSQL";// best practice is to store this in a seperate config file.
In fact, other attributes specified (Initial Catalog, Integrated Security) are not ODBC connection string attributes, hence ignored. A full list of ODBC connection attributes can be found below.
https://msdn.microsoft.com/en-us/library/ee275047(v=bts.10).aspx
I'm trying to connect to a SQL Anywhere 5 database (I know it's olllld!) with a .NET 3.5 app in WinXP and it works fine from a stand alone console app. But when I run the exact code in a plugin ,running off a separate AppDomain, (the only difference I can tell between the two) with the following code, I get the errors further below.
BTW Both are executed as the SAME user.
using (OdbcConnection connection =
new OdbcConnection(strConnect))
{
OdbcCommand command = new OdbcCommand(query, connection);
command.CommandType = CommandType.Text;
DataTable posRecordsTable = new DataTable();
connection.Open();
OdbcException Exception returns the following errors:
Index #0
Message: [Sybase][ODBC Driver]Unable to connect to database server: database engine not running
Index #1
Message: [Sybase][ODBC Driver]Invalid connection string attribute
Index #2
Message: [Sybase][ODBC Driver]Invalid connection string attribute
Index #3
Message: [Microsoft][ODBC Driver Manager] The driver doesn't support the version of ODBC behavior that the application requested (see SQLSetEnvAttr).
Does the driver on your AppDomain have the same configuration as your stand alone box? I think checking the similarity of the environments will help you. Usually such errors are resolved by looking at the config files from where the driver reads its information. Dont know much about SQL Anywhere, but in general, I've come across such issues and I fixed them by altering the connection information or the configuration file.
I have installed both IIS and SQL Server 2005 on my laptop.
Both work individualy, however when I try to connect to an DB from an ASP page I keep getting the following error:
Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "DB1" requested by the login. The login failed.
/testFiles/Connection/Connection.inc, line 5
Line 5 says:
con.open "DSN=DB1"
Can anybody tell me what the problem is?
Thanks
Below is a sample, but I think you are having a problem with credentials. Go through the configuration of the DSN and make sure it connects.
set conn = server.createobject("ADODB.Connection")
set rsuser= server.createobject("ADODB.Recordset")
conn.open CONNECTIONSTRING
sql="SELECT * FROM Table"
rsuser.Open sql,conn,1,2
rsuser.close
set rsuser = nothing
conn.close
set conn = nothing
Your Connection string "DSN=DB1" is lacking credentials at the minimum (which is why the login failed)
www.connectionstrings.com is a very useful website that will help you construct your connection string. You can select the DB you are working with and provide the details (server,DB, username,password,dsn.....) and it will help give you back the connection string.