Database Connection in C# - c#

Is there a way/code where I can use that won't require me to change my connection string everytime I move my project to another computer?
been using 2 computers with different server names, but with the same database.
PC1:
static string ConnStr = "Server=DESKTOP-Q0BI1S3;Database=ISPROJ2;Trusted_Connection=True;";
PC2:
static string ConnStr = "Server=DESKTOP//SEGUERRA;Database=ISPROJ2;Trusted_Connection=True;";
tried using: Server=(localdb)
Update: used localhost and (local) with PC1 worked fine, but these won't work with PC2
see img

I am not sure if this will work for you, but where I work everyone has their own local instance of sql server and each developer are using the db on localhost. We solve this problem by referencing the database as a dot (localhost).
"Server=.;Database=ISPROJ2;Trusted_Connection=True;"
This solution only works if all developers have their db installed as the default instance.

See here.
This may be the solution you are looking for. Use the hostname and append it to the connection string.
I also believe you may be able to use server=localhost;

You could make one computer work as a server and connect to it everytime with same connection string.
This might help you:
https://technet.microsoft.com/en-us/library/ms175483(v=sql.105).aspx

There are probably lots of libraries to solve this, but the simplest way you can do interim is to within the software identify which computer the software is run on:
static string GetConnectionString()
{
switch(System.Environment.MachineName)
{
case "PC1": //TODO:Change this to the actual machine name!
return "Server=DESKTOP-Q0BI1S3;Database=ISPROJ2;Trusted_Connection=True;";
case "PC1": //TODO:Change this to the actual machine name!
return "Server=DESKTOP//SEGUERRA;Database=ISPROJ2;Trusted_Connection=True;";
}
}
You can also make it more dynamic by reading it from the web.config/app.config:
static string GetConnectionString()
{
return ConfigurationManager.AppSettings["ConnectionString_" + System.Environment.MachineName];
}
This makes it more dynamic, and you can simply add a new connection string onto the web.config/app.config once it needs to run on a new environment.
<appsettings>
<add key="connectionstring_pc1" value="[pc1connectionstringhere!]"/>
<add key="connectionstring_pc2" value="[pc2connectionstringhere!]"/>
</appsettings>

You will find all SQL Server connection string options here.
https://www.connectionstrings.com/sql-server/
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;

Related

Get data from a database which is in a server machine

I have a winForm application which will be used by more than one persone, I want to put the database in a machine server so can everyone connect to it from this application.
I'm using SqlServer database, this database will be located in a local network.
This is the connection string I use to get data from a database located in my machine
string con = "Data Source=MSSQL1;Initial Catalog=AdventureWorks;Integrated Security=true;";
My question is what is the connection string that I should use to get data from database located in a machine server ?
Is it something like this ?
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Thanks.
Without any specific information nobody will be able to answer this for you, however This Resource. might help you find it for yourself.

SQL Server connection string specified without a computer name? How can that be?

I'm working from a code base I downloaded from a repository, and it is likely that I'm missing a system or local setting.
In Web.Config, I have this connection string:
<add name="Context"
connectionString="Data Source=InstanceName;
Initial Catalog=MyProduct;
Integrated Security=True;
Connect Timeout=15;
Encrypt=False;
TrustServerCertificate=False"
providerName="System.Data.SqlClient" />
(indentation mine)
Normally I would have expected the Data Source to be \\ComputerName\InstanceName or at least .\InstanceName if the SQL Server is on the same host. But here, nothing. The initially uploaded project had a local database, on the developer's machine. I can get the connection to work if I add .\, but I don't understand how only specifying the instance name can work. So, how can it?
The instance name is needed only if you want to connect to a named instance.
If your install of Sql Server hasn't created a named instance then the default for the instance is MSSQLSERVER and you DON'T need to specify that part on the connection string.
However, the computer name part is required but it could be expressed in various form
a point to mean the local computer
an IP address (local or not)
a server name recognized by the DNS system of your lan
the special string (LOCAL)
More info on the Data Source key could be found on MSDN docs for ConnectionString
Could it be that the InstanceName is the name of an ODBC Data Source that already has the target server configured, and the other employees have a corresponding ODBC data source set up?
The other option is that the connectionstring is modified before being passed to a data connector, so "MyMachineName" + connectionstring is happening somewhere (perhaps to separate production and development environments?
Also, double check the App_Data folder to make sure some sort of file-based database isn't being accessed.
In addition to what #Steve has already mentioned local or current machine can also be referred by a special string localhost. Please refer to below post:
What is the sql connection string I need to use to access localhost\SQLEXPRESS with Windows Authentication or SQL Authentication?

Format of the initialization string does not conform to specification starting at index 0

I have an ASP.NET application which runs fine on my local development machine.
When I run this application online, it shows the following error:
Format of the initialization string does not conform to specification starting at index 0
Why is this appearing, and how can I fix it?
Check your connection string. If you need help with it check Connection Strings, which has a list of commonly used ones.
Commonly used Connection Strings:
SQL Server 2012
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
SQL Server 2005
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
MySQL
Standard
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Specifying TCP port
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Oracle
Using TNS
Data Source=TORCL;User Id=myUsername;Password=myPassword;
Using integrated security
Data Source=TORCL;Integrated Security=SSPI;
Using ODP.NET without tnsnames.ora
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
This might help someone..
My password contained a semicolon so was facing this issue.So added the password in quotes. It was really a silly mistake.
I changed the following :
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password=pass;word" providerName="System.Data.SqlClient" />
to
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='pass;word'" providerName="System.Data.SqlClient" />
Set the project containing your DbContext class as the startup project.
I was getting this error while calling enable-migrations.
Even if in the Package Manager Console I selected the right Default project, it was still looking at the web.config file of that startup project, where the connection string wasn't present.
Check your connection string like I forget to add services.AddDbContext<dbsContext>(options => options.UseSqlServer("Default"));
It causes the error and here when I add Configuration.GetConnectionString, then it solves the issue
like now the connection is:
services.AddDbContext<dbsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
works fine (This problem is solved for .net core)
Make sure that your connection string is in this format:
server=FOOSERVER;database=BLAH_DB;pooling=false;Connect Timeout=60;Integrated Security=SSPI;
If your string is missing the server tag then the method would return back with this error.
I had the same problem. Locally the site ran fine, but on azure it would fail with the message above.
turns out the problem was setting the connectionstring in the ctor, like this:
public DatabaseContext()
{
Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
}
Does NOT work, this will:
public DatabaseContext() : base("db")
{
}
Beats me..
Referencing the full sp path resolved this issue for me:
var command = new SqlCommand("DatabaseName.dbo.StoredProcedureName", conn)
I removed &quot at the end of the connection string and it worked
Instead of
App=EntityFramework"
Used
App=EntityFramework;
Set DefaultConnection as below
<add name="DefaultConnection" connectionString="data source=(local);initial catalog=NamSdb;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.SqlClient" />
Note : In connectionString Do not include :
|x| Metadata info : "metadata=res://*/"
|x| Encoded Quotes : """
I solved this by changing the connection string on the publish settings of my ASP.NET Web Api.
Check my answer on this post: How to fix error ::Format of the initialization string does not conform to specification starting at index 0::
I had the same error. In my case, this was because I was missing an closing quote for the password in the connection string.
Changed from this
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password" providerName="System.Data.SqlClient" />
To
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password'" providerName="System.Data.SqlClient" />
In my case, I got a similar error:
An unhandled exception was thrown by the application. System.ArgumentException: Format of the initialization string does not conform to specification starting at index 91.
I change my connection string from:
Server=.;Database=dbname;User Id=myuserid;Password=mypassword"
to:
Server=.;Database=dbname;User Id=myuserid;Password='mypassword'"
and it works, I added single quotes to the password.
In my case the problem was in the encoding of the connection string.
In local it worked without problems, but when installing it in a production environment it showed this error.
My application allows to set the connection string using a form and when the connection string was copied from local to production, invisible characters were introduced and although the connection string was visually identical at the byte level it was not.
You can check if this is your problem by following these steps:
Copy your connection string to Notepad++.
Change the codification to ANSI. In Menu Encoding>Encode to ANSI.
Check if additional characters are included.
If these characters have been included, delete them and paste the connection string again.
Got this problem with SQLite in aspnetcore. I wrote
"DefaultSQLiteConnection": "MyBlog.db"
instead of
"DefaultSQLiteConnection": "Data Source = MyBlog.db"
My generated password contained few characters that were valid in AWS RDS, but for some reason my .NET app could not handle it. The solutions that worked for me, was to generate new password without characters like ` (backtick).
In my case, it was...
index: 58
but what ended up happening was the password generated had a single quote in it. SQL Server accepted that, but my connection string had trouble parsing it. Hope this saves someone at least a few minutes, because it cost me an hour to two before I relized what was going on. cheers
Hope this helps someone in the future. My connection string had blank values wrapped in double quotes, e.g. User ID="". So to resolve it I had to escape the double quotes.
Dim ConString = "Data Source=MYSERVER;User ID="";Initial Catalog=Northwinds..."
ConString = ConString.Replace("""", """""")
This also happens when you copy a web page from one solution to another, then you run your solution and find out that it has a different connection string name in the webconfig. Then you carelessly change the name of the connection string in the properties panel in the design view of the page.
Better to just change it in the code portion instead of the design.
My problem was I added database logging code to my constructor for a DB object, and this seemed to cause havoc on my azure deployment profile.
FYI - I simplified this example, in the real code this was turned off in production (but still in the code)
public class MyDB : DbContext
{
public MyDB()
{
this.Database.Log = x => { Debug.WriteLine(x); };
}
}
I had typo in my connection strings "Database==PESitecore1_master"
<add name="master" connectionString="user id=sa;password=xxxxx;Data Source=APR9038KBD\SQL2014;Database==PESitecore1_master"/>
I had the same problem and finally I managed to resolve it in the following way:
The problem was in the connection string definition in my web.config.
<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient"/>
The above worked perfect locally because I used a local Database when I managed users and roles. When I transfered my application to IIS the local DB was not longer accessible, in addition I would like to use my DB in SQL Server. So I change the above connection string the following SQL Server DB equivalent:
<add name="DefaultConnection" connectionString="data source=MY_SQL_SERVER; Initial Catalog=MY_DATABASE_NAME; Persist Security Info=true; User Id=sa;Password=Mybl00dyPa$$" providerName="System.Data.SqlClient"/>
NOTE: The above, also, suppose that you are going to use the same SQL Server from your local box (in case that you incorporate it into your local web.config - that is what exactly I did in my case).
I had the same issue, came to find out that the deployment to IIS did not set the connection strings correctly. they were '$(ReplacableToken_devConnection-Web.config Connection String_0)' when viewing the connection strings of the site in IIS, instead of the actual connection string. I updated them there, and all worked as expected
I copied and pasted my connection string configuration into my test project and started running into this error. The connection string worked fine in my WebAPI project. Here is my fix.
var connection = ConfigurationManager.ConnectionStrings["MyConnectionString"];
var unitOfWork = new UnitOfWork(new SqlConnection(connection.ConnectionString));
My problem wasn't that the connection string I was providing was wrong, or that the connection string in the app.config I thought I was using was wrong, but that I was using the wrong app.config.
For the one other unfortunate soul that is managing a legacy webforms application that uses an inline sqldatasource, along with connection strings stored in web.config, then you may get this error if you access your connection string like <%APSDataConnectionString%> instead of
<%$ ConnectionStrings:MyConnectionString %>. This happened to us when upgrading .NET from 3.5 to 4.x.
<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1"
DataTextField="value" DataValueField="id"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="select id, value from a_table">
</asp:SqlDataSource>
In my case the problem was that on the server, a different appsettings.json file was used by the application.
I had this error too and was able to solve it as follows:
I previously wrote the connectionstring to the appsettings.json into a section that I created (ConnectionsStrings (notice the extra "s") and tried to connect to my database which caused the error. It was an ASP.NET CORE application and so I wanted to connect to it with the .GetConnectionString Method (details on that here). It seems that this method implicitly searches for a connectionstring in the "ConnectionStrings"-section, which didn't exist. When I changed/corrected it to "ConnectionStrings" it worked as expected.
I had the same problem spent an entire day. The error indicates Connection string issue for sure as index 0 is connection string. My issue was in the Startup class. I used:
var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer("connection"));`
which is wrong instead use this:
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
and my problem was solved.
I had this error and it turned out that the cause was that I had surrounded a (new) tableadapter with a Using/End Using. Just changing the tableadapter to stay live for longer (duration of class in my instance) fixed this for me. Maybe this will help someone.
Sometimes the Sql Server service has not been started. This may generate the error. Go to Services and start Sql Server. This should make it work.
As I Know, whenever you have more than 1 connection string in your solution(your current project, startup project,...), you may confront with this error
this link may help you
click

Connection string for Fluent Nhibernate with MySQL

I've reviewed the post How to configure Fluent NHibernate with MySQL, but I'm relatively new to MySQL and I need to actually set up with connection string itself. I've installed MySQL as part of a WAMP install and need to fill in the actual connection string. Can someone help me by extending the linked answer to actually contain a full connection string example?
Appreciated.
Edit: I've tried several different things and I keep getting the following error message:
Can't load file FluentConfiguration.cs under d:\Builds\FluentNH-v1.x-nh3\src\FluentNHibernate\Cfg.
Check the file permission and the existence of that file.
I installed FNH via nuget, and I don't understand why it's looking at that path, as the d: drive is my CD and not a harddisk. Very confused.
The error you've pasted looks like Visual Studio trying to localise the sources to show you where the exception comes from. This is not the real exception message - you should have it somewhere there and it's probably something about wrong configuration.
If you've installed WAMP with default settings, it is configured to listen on 3306 port and have only local root account without password. So your connection string should look somehow like that:
Server=localhost; Port=3306; Database=[database_name_here]; Uid=root; Pwd=;
(Pwd= part may be not needed at all).
So you need to paste it in your App.config/Web.config's <connectionStrings> section:
<connectionStrings>
<add name="ConnectionString"
connectionString="Server=localhost; Port=3306;
Database=[database_name_here]; Uid=root; Pwd=;"
providerName="System.Data.SqlClient" />
</connectionStrings>
and then use the solution from linked question:
MySqlConfiguration.Standard.ConnectionString(
c => c.FromConnectionStringWithKey("ConnectionString")
)
Alternatively, you can paste the connection string directly in your Fluent's configuration, like this:
MySqlConfiguration.Standard
.ConnectionString.Is("Server=localhost; Port=3306;
Database=[database_name_here]; Uid=root; Pwd=;")
Anyway, this default root/no password configuration can be used only for local development and testing purposes.

C# Connecting to a SQL server with a named instance?

A client of mine has told me the program I made for them won't connect to a SQL server named instance, I have a standard SQL server with no named instance so I'm wondering how I can test this. A named instance connection string look like the one below, could the backslash be were my code fails?
Driver={SQL Native Client};Server=myServerName\theInstanceName;Database=myDataBase;
My code is as follows:
sqlServer=s.Substring(keyword.Length,s.Length-keyword.Length);
FormODBC formODBC=new FormODBC(this);
formODBC.SetSqlServer(sqlServer,dbUsername,dbPassword,database,table);
formODBC.ReadData();
How should I handle the backslash as I suspect this may be the problem?
Thanks
We have SQL servers with named instances.
Examples: myservername\sql2005.
Backslash is fine, in the conection string server name will be "myservername\sql2005", works 100% fine. You can have a "regular instance" on the same server, will be "myservername"
PS just unit test your function making connection string returns "myservername\sql2005".
Also, remember that backslash is an escape character in C# strings. If your instance name is contained in a string variable, make sure you do either:
string server = "myServer\\myInstance";
or
string server = #"myServer\myInstance";
The answer is to ensure your connection string is configurable, and set it to something like:
data source=localhost\msexpress;database=dbname;trusted_connection=true;
There is also the occassional SQL Express edition case where the name is MyServerName\SQLEXPRESS. This can trip up some people because they wouldn't think to specify the server that way.
You can extract your connection string to a config file (note this isn't necessarily secure - that will depend on how their SQL security server is set up and the account your application is running under) - then your client can just add the appropriate connection string for their server to your application's config when deployed.
Notes:
You can create a connection string by renaming a .txt file to a .udl file and running through until you can connect to your/their server.
Your unamed instance can actually be accessed by name - the machine name on which the SQL server is installed
Scott,
At the risk of stating the obvious, have you tried setting up a named instance in your own development environment? I don't actually know the answer to your question but I've never personally run into a solution where testing the scenario that is failing directly didn't help. At a minimum you ought to be able to get better debugging information as to precisely what is failing. Good luck getting this resolved.
Regards,
Chris

Categories