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");
Related
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");
Forgive me if this is easy and I have seen similar posts but I am new-ish to C# and have been struggling on this, so any help would be much appreciated.
I am trying to connect to a local DB SQL Server in Visual Studio 2012 but so far have had no luck.
I got my connection string from the properties of my local DB which in the picture is in the left hand pane.
public void connection()
{
string connectionString = "Data Source=(localdb)\v11.0;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
SqlConnection con = new SqlConnection(connectionString);
try
{
con.Open();
lblConnectionTest.Text = "Connected successfully";
}
catch (SqlException ex)
{
lblConnectionTest.Text = ex.Message;
}
}
At this point, all I am trying to do is establish a connection to the DB and basically write out "connection successful" etc if it connects.
Currently with what I have, I receive the following error:
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 am I doing wrong here?
Many thanks!
Firstly i suggest you to set conenction string in your config file.
link : http://msdn.microsoft.com/fr-fr/library/ms254494(v=vs.110).aspx
Second subject, best practise set your connection in using bloc
link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx
DataSource is your target sql server, access properties of your server and get name, but for your case i think that you want access remotly, so ensure that your firewall server is configured to allow.
If you are in C#, you can create an application config file (App.config), which will be having the connection string with its name.
this is sample code in the app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="myConnString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AppsTest\Nov17RoomBooking\dbRoomBooking.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then Your code should look like this:
private static string sqlConnectionString = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;
private void DeletingDataBase()
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string sqlQuery = "SELECT, INSERT, UPDATE, DELETE";
cmd.Connection = sqlConn;
cmd.CommandText = sqlQuery;
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch { }
finally
{
cmd.Connection.Close();
}
}
}
}
I encourage you to start learning LINQ to SQL. In my opinion it's the better way for handling data and interacting with the database. I see you're trying to connect to MySql, but i really don't know if that's possible while using LINQ. I hope someone answers this question.
You can actually solve all of this with few clicks, im using visual studio 2012 and by pulling my ms sql table to the aspx file it actually forms the table on its own and even builds all the connection strings for you.
Your Connection String is wrong.
Correct Syntax for MS SQL SERVER 2012 Express (Built in )
lets suppose my DataBase File is at the path :
C:\Users\Zohair\Documents\Visual Studio 2012\Projects\Learning2\Learning2\Sample.mdf
My Connection String will be :
SqlConnection conn = new SqlConnection("Data Source=(localdb)\\v11.0;Integrated Security=true;AttachDbFileName=C:\\Users\\Zohair\\Documents\\Visual Studio 2012\\Projects\\Learning2\\Learning2\\Sample.mdf");
NOTE: If it gives an error when using single slashes (\) then replace them with double slashes (\\)
I've recently started programming asp.net with C# (using VS2008) and I wrote my first web application that connects to a database. First version worked ok but now there are some problems once I modify it. I'm giving the examples below which will depict the situation:
1) Works OK. Program connects to a database and uses a function DeleteAllRecords() to perform an action on it; important to note that I created the database to connect to in SQL Server Management Studio.
Code behind page of the button-click event handler:
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("przemek8");
SqlCommand myCommand = new SqlCommand("DELETE FROM table8", dbConnection);
myCommand.ExecuteNonQuery();
}
catch (SqlException exception)
{
Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
}
dbConnection.Close();
}
2) the second time I didn't use the database made in SQL SM Studio but I added a new database element from Visual Studio itself (Website -> Add New Item). I added some fields to that database and I also configured a GridView to show the database which is working. The problem, however, is that when I want to connect the Gridview to the database created before in SQL SM Studio, it doesn't work - when configuring the connection it won;t let choose the database file, saying:
You don't have permission to open this file. Contact the owner or an administrator to obtain permission.
It seems to me that the reason for that may be trivial but I cannot sort it out.
Just to note that all that database files were created SQL SM Studio in its default destination on disc C.
3) Not being able to connect with the GridView to the database created by SQL Server I continued working with the database added by Visual Studio itself. It was working with the GridView so I used the function to interact with it (delete all the records) - the same that was used at point 1) but with database now.
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename='D:\\WebSite1\\App_Data\\mydtb.mdf'; Integrated Security=true; User Instance=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("mydtb");
SqlCommand myCommand = new SqlCommand("DELETE FROM Table1", dbConnection);
myCommand.ExecuteNonQuery();
}
catch (SqlException exception)
{
Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
}
dbConnection.Close();
It does not connect to that one and the error message is:
Error code 911: Database 'mydtb' does not exist. Make sure that the name is entered correctly.
I'm new in this field, but should the data source in this case (connecting to the database created in Visual Studio) be Data Source=.\\SQLEXPRESS; as it is when the database is created in SQL Server Management Studio?
Thanks a lot for any help and suggestions!
asp.net excited beginner:-)
The problem your having with regards to connecting to the database on a server is because of
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
The best way to do this is to go to your Web.config file and find the block and add a connection to your database in there.
eg
<add name="ConnectionString" connectionString="Data Source=YOUR SERVER;Initial Catalog=YOUR DATABASE;User ID=YOUR USER ID;Password=YOUR PASSWORD" />
then you can just call the connection string accross your whole project whenever you need to use it.
Also with regards to VS2012. There are very few companies using that IDE at the moment so your probably better off learning VS 2010 in the most part but i would agree that VS2008 is fairly out of date now
i think this will help
SqlConnection dbConnection = new SqlConnection("Data
Source=.\\SQLEXPRESS;Integrated Security=true; initial
catalog=database name; uid=servername ; password=yourpassword");
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.
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.