Connecting to local SQL Server database using C# - c#

Suppose I have created a SQL Server database called Database1.mdf in the App_Data folder in Visual Studio with a table called Names.
How could I establish a connection to read the table values using C#?
So far I've tried something like this:
SqlConnection conn = new SqlConnection("Server=localhost;Database=Database1;");
conn.Open();
// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Names";
But I get an error:
database not found/error connecting to database

In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();

If you're using SQL Server express, change
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/

SqlConnection c = new SqlConnection(#"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");

You try with this string connection
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;

I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.
Hope that helps.

Visual Studio 2019 (and probably a few previous versions).
View -> SQL Server Object Explorer
Top of the tree is 'SQL Server'
Under 'SQL Server', are couple of '(localdb)....'
Expand the (localdb)... -> Databases until you find your db.
Database Name (eg. Database1) -> Right-click -> Properties, and scroll the many properties (eg. "ANSI
NULL Default"). Find the "Connection string" property, copy the value
into your code, and you're running.

Related

SqlConnection, I'm using SQL Server, not LocalDB; so how to

So, in the tutorial I was checking, he uses a Database and connect it using this
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\RANBAH~1\Documents\testlogin.mdf;Integrated Security=True;Connect Timeout=30");
Although, I use SQL Server Management 17, which mean I have a server, So how do i get my SQL Connect Data Source? because afterward he uses it for
SqlDataAdapter sda = new SqlDataAdapter("select count(*) from login where username ='" + textBox1.Text + "' and password='" + textBox2.Text + "'", conn);
Any clue ?
Inside your project, in VS, connect to the server. Once you are on the server explorer, right click on the database to get the connection string. When you check the properties for the database, you should be able to see it.
You cannot get the connection string from SSMS, though you can get all the information for the connection string. Then, you can use those information to create your own connection string using this website: https://www.connectionstrings.com/ Just check which is better suited for you.

How to connect an application to a SQL Server using IP Adress in C#?

My problem is that I have created a SQL Server database but I access it locally, only from my own computer. What I want to do is to connect the app to a server and to save all the data there.
The code I used to connect to the SQL Server database is:
SqlConnection con = new SqlConnection(#"Data Source=(localdb)\v11.0;AttachDbFilename=C:\Users\donca\Desktop\Memo\Memo\ContNou.mdf;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("SELECT * FROM [dbo].[Cont] WHERE Nume_utilizator = #Nume_utilizator and Parola = #Parola;", con);
cmd1.Parameters.AddWithValue("#Nume_utilizator", this.Nume_utilizator.Text);
cmd1.Parameters.AddWithValue("#Parola", this.Parola.Text);
cmd1.Connection = con;
con.Open();
My question is: how can I change this to connect and access data from a SQL Server and save data there?
Just change the connection string:
"Data source=ServerName\InstanceName;"
You can use the IP address instead of the servername.
The default instance name is MSSQLSERVER.
Make sure you turn on "Remote connections" on the distant server. You can use Management studio -> Server properties -> connections -> Allow remote connections.
If it dosn't work check that the TCP/IP protocol is activated for you instance.
You can find it in SQl Server Configuration Manager.
You just have to change your connection string. That's all. For an example, if your server name is CORP and the SQL instance name is SQL2012, your connection string will be like this.
SqlConnection con = new SqlConnection(#"Data Source=CORP\SQL2012;Initial Catalog=ContNou;Integrated Security=True");
In case if you cannot find the SQL server by its name, you can use the IP too.
SqlConnection con = new SqlConnection(#"Data Source=10.4.2.208;Initial Catalog=ContNou;Integrated Security=True");

Microsoft Visual Studio SQL server connection - invalid pointer

So, I want to create a SQL database in Microsoft SQL Management Studio and connect it to Microsoft Visual Studio. I linked the database to Visual Studio and it worked. Now, I want to open that connection to test it with a button on a windows form application. Every time I try, it says "invalid pointer" but the database name is correct. I don't know what is wrong.
I still get the invalid pointer error...My instance name is DESKTOP-BJSAO6B but it doesnt seem to work...
You need provide a proper connection string like
string connectionString =
"data source=.\SQLEXPRESS;initial catalog=student;integrated security=True;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
MessageBox.Show("You are connected");
}
where SQLEXPRESS - name your MSSQL instance ( may be different). More you can see here
For Ex:
string connectionString = "Data Source=Server-Name; Initial Catalog= Database-Name;Integrated Security=True"; //If you are using a local Database.
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
MessageBox.Show("You are connected");

ConnectionString Database c#

I am create a database utility and I seem to not be able to get my connectionstring correct.
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
I believe this is in the correct format. As for the data source, my sql server is SQLExpress which runs sql server 2008 R2. My database is named ConfigurationData. Am I missing something?
When I run it, it opens the database - I assume it does since it does not through exception - but when I try inserting into a table, it does not actually insert it yet it executes the command.
conn.Open();
try
{
SqlCommand comm = new SqlCommand("INSERT INTO Test " + "(id,number) " + " VALUES(" + 10 + " , " + 12 + ")", conn);
comm.ExecuteNonQuery();
Console.WriteLine("Database is created successfully", "MyProgram");
}
catch (Exception ex)
{
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
EDIT
Just remembered that I had answered a similar question a while back. Check it out:
Why can't I insert data into local database (SQL Compact Edition) with C#?
I don't think it is the connection string issue. But for your reference, a good site to refer to is http://www.connectionstrings.com/sql-server-2008/
You would need one of these:
Attach a database file, located in the data directory, on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;
Attach a database file on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
Using an User Instance on a local SQL Server Express instance
The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL
Server instance to a user with limited administrative rights on the computer.
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure 'user instances enabled', '1'. To disable the functionality execute sp_configure 'user instances enabled', '0'.
try (local) instead of dot, dot is not recognized in Win XP
conn.ConnectionString =
"Data Source=(local)\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
You're SQL Statement isn't right also, and you should use parameters, but here is what you should have
SqlCommand comm = new SqlCommand("INSERT INTO Test (id, number) VALUES('" + 10 + " ', '" + 12 + "')", conn);
Why not just use the SqlConnectionStringBuilder class?:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #"(local)\SQLExpress";
builder.UserInstance = true;
builder.IntegratedSecurity = true;
builder.AttachDBFilename = "|DataDirectory|ConfigurationData.mdf";
SqlConnection conn = new SqlConnection(builder.ConnectionString());
The output:
"Data Source=(local)\\SQLExpress;AttachDbFilename=|DataDirectory|ConfigurationData.mdf;Integrated Security=True;User Instance=True"
One of the way to do this is to add your connection string in web.config file as shown below:
Jus click on the properties of database on the database explorer. There you will find connectionstring in its properties. Jus add it in connectionstring below.
<configuration>
<connectionStrings>
<add name="ConnectionName" connectionString="your connection string" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Then in the page you can store it in string or directly refer to your connection as shown below:
Connection con=new SqlConnection();
con.ConnectionString=ConfigurationManager.ConnectionStrings["connString"].ToString();
and I suspect your insert statement is not properly declared.
Just try this:
SqlCommand comm = new SqlCommand("INSERT INTO Test (id,number) VALUES('10' ,'12')", con);
That's all from my part... Hope it helped you..

How to backup from .mdf database that I created

I created a .mdf database file with Visual Studio 2008. I can retrieve and insert data into database but when I want to backup I receive an error.
My code:
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|C:\test\Data|\DB.mdf;Integrated Security=True;User Instance=True";
connect = new SqlConnection(con);
connect.Open();
SqlCommand command = new SqlCommand(#"backup database [" + System.Windows.Forms.Application.StartupPath + "\\Data\\DB.mdf] to disk ='"+str+"' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
The error is:
error : invalid value for key 'attachdbfilename'.
Seems like your connection string is incorrect.
Try this one:
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\test\Data\DB.mdf;Integrated Security=True;User Instance=True";
For more options, have a look at: http://www.connectionstrings.com/sql-server-2005
This is for SQL Server 2012 and .NET 4.0.1 only.
If you have those, you should be able to use AttachDbFilename.
Anyway, if you have an .MDF for embedded database and the instance is not running, you can just copy .MDF and .LDF to back up.
just use your connection string as
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["<your connection string name from your app.config file>"].ConnectionString);
i tried it and it worked for me.

Categories