Fail to connect to SQL Server database - asp.net

I am using VS 2008 .NET 3.5 & have a SQL Server database file in App_Data. When I click on "Test Connection" of database it succeeds. When I try to connect it through code, it fails. After trying to find & solve the problem reading so many sites, I think I am confused with the connection string.
My code is :
string sql = "select count(*) from LoginDB where loginUserName = #userName and loginPassword = #password";
string conStr = ConfigurationManager.ConnectionStrings["VinciConnectionString"].ConnectionString;
statusLbl.Text += "\n Conn Str = " + conStr;
conn = new SqlConnection(conStr);
statusLbl.Text += "\n Executed Conn : " + conn.ToString();
SqlCommand cmd = new SqlCommand(sql, conn);
statusLbl.Text += "\nconn DB = " + conn.Database;
In the output I get :
Conn Str = server=localhost;database=VincitoreDB.mdf;uid=VTSONY\Vikram10;Password=000;
Executed Conn : System.Data.SqlClient.SqlConnection
conn DB = VincitoreDB.mdf
SQL = System.Data.SqlClient.SqlCommand
The error message that I get here is :
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)
The DB "Modify Properties"-"Advanced" tab shows this :
Original connection string was :
<connectionStrings>
<add name="VinciConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VincitoreDB.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
After trial & error, right now it's :
<connectionStrings>
<add name="VinciConnectionString"
connectionString="server=localhost;database=VincitoreDB.mdf;uid=VTSONY\Vikram10;Password=000;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Can anyone please help me figure out what & why am not able to connect to the database? Have spend lots of hrs trying to figure out reading lots of forums, but no success. If this the problem of connection string or something else?
Please help me out. Any help is highly appreciated.
Thanks

Enable in your Sql Server Configuration manager under SQL Server Networki configuration > Protocols fro SQLExpress > TCP IP - Enabled after this restart the computer or the service.
In connection string provide your computers name for example: MY-PC\SQLEXPRESS

Related

How to connect to MS SQL Server using ODBC and DBI in R

I'm having difficulty making a connection to my MS SQL Server from R.
I believe I'm using the right driver, I checked what drivers I had listed and picked the same one that I'm using in DBeaver for the connection to the same database:
odbcListDrivers() %>% filter(name %like% "SQL Server" & !name %like% "Teradata")
My connection string looks as follow:
db_conn <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "Server_address",
Database = "Database_Name",
UID = "myName",
PWD = "myPWd",
Trusted_Connection = "True",
Port = 1433,
ApplicationIntent = "ReadOnly"
)
I get the following error:
Error: nanodbc/nanodbc.cpp:1021: 01S00: [Microsoft][ODBC SQL Server Driver][SQL Server]The target database ('Database_Name') is in an availability group and is currently accessible for connections when the application intent is set to read only. For more information about application intent, see SQL Server Books Online. [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute
I can connect to the same database using DBeaver and have specified the the connection has applicationIntent = readonly
Is there some other connection string property I need to include to make a connection?
Turns out that I was using the correct connection string properties but the server was running in cluster mode and therefore I needed to append 'CLS' to my database name.
My final connection string looks as follows:
db_conn <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "SomeDBcls.xx.yy.zz.com",
Database = "NameOfSchema",
UID = "TheGoat",
PWD = rstudioapi::askForPassword("Database password"),
Trusted_Connection = "Yes",
Port = 1433,
applicationIntent = "readonly"
)

TNS:could not resolve service name error in asp.net

I am connecting to oracle database through asp.net. My code is running well on server machine but when I try to run it on local machine I am getting TNS error.
My connection Strings are :
<add name="oraclebldb" connectionString="DataSource=SKM.SMEBANK.ORG;Persist Security Info=True;User ID=bldb;Password=bldb;Unicode=True" providerName="System.Data.OracleClient"/>
<add name="OraConnectionString" connectionString="Data Source=skm;Persist Security Info=True;User ID=bldb;Password=bldb;Unicode=True" providerName="System.Data.OracleClient"/>
There must be tnsname.ora file in your local machine where you must be having oracle client installed.
go to
localdrive:\oracle\product\oracle version\client_1\Network\admin
Note: localdrive must b C or D based on location given at the time of installation
or
go to command prompt and type path which will give you the oracle home directory path of your local machine.
See below definition for your reference
mydb =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = myserver )(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = mydb)
)
)

Cannot access remote SQL Server from IIS 7 web app

I've been trying to move the database from an application to another server without success.
I'm getting the following error message when opening the web application:
"Login failed. The login is from an untrusted domain and cannot be used with Windows authentication."
The user is a domain user configured as identity in the app pool and also has full access rights on the SQL Server (I can access the DB remotely over SQL Server Management Studio).
I tried the following:
enabled the Do not require Kerberos preauthentication option in AD
added the SQL account to "Access this computer from network" Policy under Local Security Policy -> Local Policies -> User Rights Assignment -> Access this computer from network"
Added the entry "127.0.0.1 localhost" to local hosts file
The domain user is local admin on the web and database server.
Web.Config / App Settings:
<appSettings>
<add key="DBServer" value="remoteSQLDBHostName" /> -- previous: value="."
<add key="DBName" value="WebDB" />
<add key="DBProvider" value="System.Data.SqlClient" />
<add key="DBMetadataBase" value="res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl" />
</appSettings>
The connection string is build dynamically in the application (sample snippet):
var sqlBuilder = new SqlConnectionStringBuilder
{
DataSource = serverName,
InitialCatalog = databaseName,
IntegratedSecurity = true
};
var providerString = sqlBuilder.ToString();
var entityBuilder = new EntityConnectionStringBuilder
{
Provider = providerName,
ProviderConnectionString = providerString,
Metadata = String.Format(metadataBase, Constants.ModelName)
};
var connStr = entityBuilder.ToString();
return connStr;

Provider error 80040e21 Classic ASP SQL Server 2008

I'm trying to connect to SQL Server 2008 from a Classic ASP page:
Set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = "
Provider= SQLOLEDB.1
DataBase= MYDBNAME
Server= SERVERNAME\INSTANCE
Integrated Security = True
Trusted_Connection=Yes
Persist Security Info = False"
conn.Open -> error 80040e21 Multiple-step OLEDB operation generated errors
sql = "select * from UsersQuery where ID=" & ID
Set rs = conn.Execute(sql)
In SQL Server Log I can see that the connection was successful:
Login succeeded for user 'dbuser' Connection made using Windows
Authentication.
What is causing the error?
Thank You.
Does it works ?
Provider=SQLNCLI11;Server=ServerName\Instance;Database=MYDBNAME;Integrated Security=SSPI;DataTypeCompatibility=80;MARS Connection=True;

Connection string - Keyword not supported: 'initial catalog'

I am using Webmatrix.data's Database entity to create a database connection, however it doesnt like my connection string. I am running it from MVC ASP.net.
Ive tried changing it to server / database, but still errors the same. Where am I going wrong?
using (var db = Database.OpenConnectionString(#"Data Source=MY-HP\Serv;Initial Catalog=MyDBSQL;User ID=sa;Password=password"))
{
var items = db.Query("SELECT * FROM TaskPriority");
}
Exception Details: System.ArgumentException: Keyword not supported: 'initial catalog'.
check here: Database.OpenConnectionString Method (String, String)
try to specify the provider name as second parameter, from the MSDN example:
var connectionString = "Data Source=.\\SQLExpress;Initial Catalog=SmallBakery;Integrated Security=True";
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
ARRRRHHHHHH!!!!!
This is the second time I've run into this, grrrh - wasted hours on it.
Error:
The server encountered an error processing the request. The exception message is 'Keyword not supported: 'initial catalog;MyDatabase;data source'.'. See server logs for more details. The exception stack trace is:
Stacktrace:
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable
parsetable, String connectionString, Boolean buildChain, Hashtable
synonyms, Boolean firstKey) at
System.Data.Common.DbConnectionOptions..ctor(String connectionString,
Hashtable synonyms, Boolean useOdbcRules) at
System.Data.SqlClient.SqlConnectionString..ctor(String
connectionString) at
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String
connectionString, DbConnectionOptions previous) at
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey
key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions&
userConnectionOptions) at
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey
key) at
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString,
SqlCredential credential)
This was my faulty connection string:
<add name="Production" connectionString="Password=Secret;Persist Security Info=True;User ID=MyUserID;Initial Catalog;MyDatabase;Data Source=aquickborwnfoxjumpedover.us-west-2.rds.amazonaws.com,1433" providerName="System.Data.SqlClient" />
Looks good right? WRONG
Eventually I spotted the semi-colon here:
Initial Catalog;MyDatabase
To correct it, I used an equal sign:
Initial Catalog=MyDatabase
The correct connection string:
<add name="ConnString" connectionString="Password=Secret;Persist Security Info=True;User ID=MyUserID;Initial Catalog=MyDatabase;Data Source=aquickborwnfoxjumpedover.us-west-2.rds.amazonaws.com,1433" providerName="System.Data.SqlClient" />
You can use the below code
Config file :
<connectionStrings>
<add name="con" connectionString="Data Source=ServerName;Initial Catalog=master;Integrated Security=SSPI;" providerName="System.Data.SqlClient"></add>
</connectionStrings>
cshtmlfile :
var db = Database.Open("con");
var selecteddata = db.Query("select * from movie");
I ran into the error in one of the IdentityServer quickstarts.
Had to replace
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
With
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Using
Microsoft.EntityFrameworkCore.SqlServer
Because obviously my DB was a Microsoft SQL Server and not SQLite.
For me I was getting this error because I was using a templated solution. Unbeknownst to me the template only installed support for sqlite. I had to install Microsoft.EntityFrameworkCore.SqlServer and change the calls in my code from UseSqlite to UseSqlServer.
You need to check your connection string.
I received the error because I had db(instead of 'Database') in my connection string.
"DevConnection": "server=DEL1-XX-XXXX;db=DonationDb;user=sa;password=XXXX"
Updating the above connection string(db to Database) should solve the problem. Below is the working connection string.
"DevConnection":"server=DEL1-XX-XXXX;Database=DonationDb;user=sa;password=QwerXXXX"
I suggest:
You can check your connection string format clearly especialy " and ". In my case this is:
You may try generate db by EF again.

Resources