SQL connection string for database on network - c#

I want to connect to a database on a host except localhost, my DBMS is SQL Server and I'm using ado.net, like this:
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("insert into st (ID,Name) values ('"+cnt.ToString()+"','havijuri');", con);
//some sql commands.
con.Close();
what should I use as the constr (connection string), and with these information:
host IP: 10.15.10.12
the file is database1.mdf,
in this directory(on the host): D:\Project1\DataBase
Tell me if any other information is needed

If the mdf file is not attached to an instance of sql server and you want to connect to the database while it does not exist on the same machine as your application, you need first to copy the database to the server with the mentioned IP and attach it to an instance of sql server installed on that server.
The connection string in this case -if you have a domain and will be authenticated to the database server by windows authentication- will be as follows:
"data source=10.15.10.12; integrated security=SSPI;initial catalog=database1"
Or you can create a sql server user on the database sever and connect using the following connection string:
"data source=10.15.10.12; initial catalog=database1;user id=<username>;password=<password>"

http://www.connectionstrings.com/sql-server-2008

create a file on your desktop called test.udl open it up and follow the steps to connect to your database then click test to make sure it works. then open the file in notepad, it will be 1 line and contain the connection string

and with these information:
•host IP: 10.15.10.12 •the file is
database1.mdf, •in this directory(on
the host): D:\Project1\DataBase
You can not. Database file attachment is only supported by express, not by the real server. ForSL Server, you need the database name (which can be different than the file name) and the database must e mounted first by the DBA. You also need acces to the server (as in: username, password). The security credentials are - again - determined by the DBA.
So, you miss the critical information (name of the database, username, password) to access a database server.

Related

Connecting to Microsoft Access file at server

I have this access.mdb at server folder. My webpage will connect to this access database using :
"Data Source=" & Server.MapPath("/cloud/login/mydatabase.mdb")
so the server path will be www.abc.com/cloud/login/mydatabase.mdb.
How can I connect to this database from my computer?
using C# or access
string connectionString = "PROVIDER=Microsoft.ACE.OLEDB.12;DATA SOURCE=www.abc.net/cloud/login/login.mdb;";
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
I tried connecting to server database using Access/ExternalData and point to the server path but I am unable to connect.
Reason why I am doing this is because when I change data, I need to use FTP to download this .mdb and change and upload back. Which is very troublesome.
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=\\serverName\cloud\login\login.mdb;
Note: The Server name is where you have ur mdb , so put that name. The folder which u access should be shared for access.

Saving to database from WinForm

I'm having trouble to save details about a movie in my database. I know the name giving is not good, but I have just made 1 textbox for input right now, as I am getting desperate. Can anyone tell me what I have done wrong in my code.
If it helps I having the following error which suggests that it can't connect to my localDB but I am not sure.
Error from code :
Code:
private void btnRes_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = ("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True");
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
com.CommandText = ("INSERT into movieTable (movieID, movieName, movieLength, movieDescription) VALUES ('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"');");
com.ExecuteNonQuery();
sc.Close();
Your local database is not accessible over network. Try the following -
Check whether server is on
Check whether firewall is not blocking the Program
Check whether Named Pipes and TCP/IP is enabled in SQL Configuration manager. To access SQL Configuration Manager, go to Start > SQL Server (Version) > SQL Configuration Manager. Then expand Client Configuration (if it's x64 then there will be 2 item , click that does not have 32 with it).
From the right pane select Named Pipe, Vias and TCP/IP and enable all and restart server.
Make sure you are using correct instance name. MQL Server Enterprise or Standard editions might not have instance names but also can be installed with instance name. See in you SQL configuration manager that you are using the proper instance name.
Then try again.
First of All check the Authentication mode of the Sql Server whether it is in Windows Authentication Mode or SQL Server Authentication Mode
Secondly Check whether the service of the SQL Server is in running state or not
If the SQl Server installation mode is SQl Server Authentication Mode then the connection string used is :
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
If the SQL Server installation mode is Windows Authentication then the connection string is :
Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;

How to get the connection String from a database

I have created a database with SQL Server Management Studio, I would like to now use it in my C# application. I need the connection string?
Where can I find the connection string, and where is my database stored?
Do I have to publish it or something like that, or is it in my documents somewhere?
using (var conn = new SqlConnection("your connection string to the database"))
How do I obtain the connection string? Where can I find the connection string to copy paste into the above section?
How to I publish my database so that Visual Studio can pick it up? Then I can just pull the connection string of there?
The easiest way to get the connection string is using the "Server Explorer" window in Visual Studio (menu View, Server Explorer) and connect to the server from that window.
Then you can see the connection string in the properties of the connected server (choose the connection and press F4 or Alt+Enter or choose Properties on the right click menu).
Advanced connection string settings: when creating the connection, you can modify any of the advanced connection string options, like MARS, resiliency, timeot, pooling configuration, etc. by clicking on the "Advanced..." button on the bottom of the "Add connection" dialog. You can access this dialog later by right clicking the Data Connection, and choosing "Modify connection...". The available advanced options vary by server type.
If you create the database using SQL Server Management Studio, the database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express / localDB installed on your machine for this to work.
A very simple way to retrieve a connection string, is to create a text file, change the extension from .txt to .udl.
Double-clicking the .udl file will open the Data Link Properties wizard.
Configure and test the connection to your database server.
Close the wizard and open the .udl file with the text editor of your choice and simply copy the connection string (without the Provider=<driver>part) to use it in your C# application.
sample udl file content
[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;Initial File Name="";Server SPN=""
what you need to copy from it
Integrated Security=SSPI;Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;
If you want to specify username and password you can adopt from other answers.
Tutorial: https://teusje.wordpress.com/2012/02/21/how-to-test-an-sql-server-connection/
Open SQL Server Management Studio and run following query. You will get connection string:
select
'data source=' + ##servername +
';initial catalog=' + db_name() +
case type_desc
when 'WINDOWS_LOGIN'
then ';trusted_connection=true'
else
';user id=' + suser_name() + ';password=<<YourPassword>>'
end
as ConnectionString
from sys.server_principals
where name = suser_name()
If you have installed and setup MS SQL Server and Management Studio, go to Visual Studio (Visual Studio not SQL Server Management Studio).
1] In Visual Studio go to Tools -> Connect to Database.
2] Under Server Name Select your Database Server Name (Let the list Populate if its taking time).
3] Under Connect to a Database, Select Select or enter a database name.
4] Select your Database from Dropdown.
5] After selecting Database try Test Connection.
6] If Test Connection Succeeds, Click Ok.
7] In Visual Studio go to View -> Server Explorer.
8] In Server Explorer window, Under Data Connections Select your Database. Right Click your Database -> Click Properties.
9] In Properties window you will see your Connection String.
On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
on myServerAddress, write the name of your installed instance (by default it's .\SQLEXPRESS for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.
edit
You will need to omit username and password for windows authentication and add Integrated Security=SSPI.
My solution was to use excel (2010).
In a new worksheet, select a cell, then:
Data -> From Other Sources -> From SQL Server
put in the server name, select table, etc,
When you get to the "Import Data" dialog,
click on Properties in the "Connection Properties" dialog,
select the "Definition" tab.
And there Excel nicely displays the Connection String for copying
(or even Export Connection File...)
If one uses the tool Linqpad, after one connects to a target database from the connections one can get a connection string to use.
Right click on the database connection.
Select Properties
Select Advanced
Select Copy Full Connection String to Clipboard
Result: Data Source=.\jabberwocky;Integrated Security=SSPI;Initial Catalog=Rasa;app=LINQPad
Remove the app=LinqPad depending on the drivers and other items such as Server instead of source, you may need to adjust the driver to suit the target operation; but it gives one a launching pad.
put below tag in web.config file in configuration node
<connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
providerName="System.Data.SqlClient" />
then you can use above connectionstring, e.g.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();
The sql server database will be stored by default in the following path
<drive>:\Program Files\Microsoft SQL Server\MSSQL.X\MSSQL\Data\
, where <drive> is the installation drive and X is the instance number (MSSQL.1 for the first instance of the Database Engine). Inorder to provide the connection string you should know what is the server name of the sql server database, where you have stored followed by instance of the database server.
Generally the server name will be like the ip address of the machine where the database is attached and the default instance will be SqlExpress
A connection string contains Data Source name i.e., server name, Initial catalog i.e., database name, user id i.e., login user id of the database, password i.e., login password of the database.
Easiest way my friends, is to open the server explorer tab on visual studio 2019 (in my case), and then try to create the connection to the database. After creating a succesful connection just right click on it and go to propierties. There you will find a string connection field with the correct syntax!...This worked for me because I knew my server's name before hand....just couldn't figure out the correct syntax to run my ef scaffold...
If you created Connection Manager in your project then you can simply pull the connection string from there.
String connection = this.dts.connections["<connection_manager_name>"];
And use this connection in:
using (var conn = new SqlConnection(connection))
Please correct me if I am wrong.
SqlConnection con = new SqlConnection();
con.ConnectionString="Data Source=DOTNET-PC\\SQLEXPRESS;Initial Catalog=apptivator;Integrated Security=True";

Problem In Open Or Use master.mdf database in C#

I define Sql_Cmd And Other sql variable that need before
and Now write this code:
string strConnection2 = "Data Source=.\\sqlexpress;AttachDbFilename=master.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection sqlcon2 = new SqlConnection(strConnection2);
string sql = "select * ";
Sql_Cmd.CommandType = CommandType.Text;
Sql_Cmd.CommandText = sql;
Sql_Cmd.Connection = sqlcon2;
try
{
sqlcon2.Open();
Sql_Cmd.ExecuteNonQuery();
}
catch (SqlException Error_Exception)
{
//FormError1 = new FormErrorInDataBase();
//FormError1.Show();
}
When I want to open sqlcon2 I see this error:
An attempt to attach an auto-named database for file master.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Please help me - how can I open master database and then use select query for this database, and what is the connection string for master.mdf?
Can I write the directory of mater.mdf such as C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\master.mdf or is it enough that I write AttachDbFilename=master.mdf?
Are you trying to open 'the' master database? The system database called 'master' is used internally by SQL Server and should not / does not need to be opened or attached in this way. If not, you'll have to call your database something other than 'master' - that is a reserved database name.
Check your parameters again. The right syntax to add an .mdf-file is as follows. Attach a database file on connect to a local SQL Server Express instance:
Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.
See: connectionstrings.com
master database is the system database that contains system information about SQL Server instance, information about databases contained in this instance and so on. This database is opened automatically when SQL Server starts.
So, when you want to connect to SQL Server, master database is already exist and cannot be attached. Information about this database you can see here
I cannot understand why you need to attach this database. Maybe you don't need to attach this database, but only connect to it? If so, you need to change th code:
string strConnection2 = "Data Source=.\\sqlexpress;initial catalog=master;Integrated Security=True;Connect Timeout=30;"

can not open database on localnetworks

I write a win app,and i create my database on the server by codes.now every client on local network can't login to my database and this error occured
:"cannot open database "test" requested by the login.the login failed for user "farzane".
the connectionstring for to make my database is:
ConnectionString=#"Data Source=SERVER\SQLEXPRESS;Initial Catalog=master;Integrated security=SSPI;Persist Security Info=False";
and it's my connection string for open my database:
ConnectionString=#"Data Source=SERVER\SQLEXPRESS;Initial Catalog=test;Integrated security=SSPI;Persist Security Info=False";
how can give permission for logining to my database to any client with codes???
thanks in advance for any help.
I would check two things here:
Ensure that your SQL Express install allows remote connections. (Simple to check using SQL Server Studio Manager).
You are using trusted authentication in your connection string. You have to explicitly give users on your domain access on the database. You will have to this in SQL Server.
are you using a domain for the network ?
if yes then make sure that the user name has access to the SQL server
if you're using a workgroup then it won't work... just create a user on the sql server and use the sql server auth at the server and connection string
Points i concluded:
First of all the users who are going to create the database , must be authorized to use master database. So ask your admin to allow permission to farzanne.
If you(farzanne) are admin, set farzanne to create databases permission to true. Or the other users that might create dbs. Also, if you allow all users then it will be difficult to handle, your application, so be alert.
What is the need of the dynamically createing database from application. Is this a part of setup or deployment or you are creating an isolated space that is different user different database.

Categories

Resources