I'm in Visual Studio 2013, using SQL Server Express 2012, on Windows 7 OS.
With C# code, I CAN connect to the database and query. For example:
using (SqlConnection sqlConnection = new SqlConnection("server=MYSERVER\\SQLEXPRESS; Trusted_Connection=yes; database=MyDatabase; connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT count(*) FROM tblData";
cmd.Connection = sqlConnection;
sqlConnection.Open();
int count = (int)cmd.ExecuteScalar();
Console.WriteLine(count); // I get the correct answer.
}
}
That works. My problem is that if I use Server Explorer within Visual Studio, I cannot connect to the database via that route. In the Add Connection, MyServer does appear in the server dropdown, but the database dropdown is empty. When I click Test Connection or OK (leaving Database empty or entering MyDatabase), I get the error: Server was not found or was not accessible.
So I can connect via C# code, but not with Server Explorer. What am I missing?
Thanks.
You have a named instance (SQLExpress) of the SQL Server. In the connections window, try typing in the server name as:
MYSERVER\SQLEXPRESS
Related
I have created a SQL DataBase (DatabaseTest.mdf) in Visual Studio 2019 Preview (.NET Core 3.1, Windows Form Application).
It is my first time, I am trying to do this. I run the database locally on my computer.
The database consists of 4 columns:
First Name
Last Name
PhoneNumber
Salary
Now, I am trying to use C# to programatically ADD a row with information to this database.
The code is the below:
using System.Data.SqlClient;
private void button1_Click(object sender, EventArgs e)
{
string connectionString = GetConnectionString();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("sp_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#First Name", "Peter");
cmd.Parameters.AddWithValue("#Last Name", "Smith");
cmd.Parameters.AddWithValue("#PhoneNumber", "5548945667");
cmd.Parameters.AddWithValue("#Salary", 50000);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i != 0)
{
MessageBox.Show(i + "Data Saved");
}
}
static private string GetConnectionString()
{
return "Data Source=(LocalDB)/MSSQLLocalDB;AttachDbFilename=C:/Users/andre/source/repos/TestDatabaseCreation/DatabaseTest.mdf;Integrated Security=True";
}
However, when I now run this code by clicking on the button. I receive this error:
System.Data.SqlClient.SqlException: '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)'
Win32Exception: Network path not found.
I have copied this connection string from the DatabaseTest.mdf properties exactly. So the path to the DatabaseTest.mdf below is correct etc
"Data Source=(LocalDB)/MSSQLLocalDB;AttachDbFilename=C:/Users/andre/source/repos/TestDatabaseCreation/DatabaseTest.mdf;Integrated Security=True"
I wonder what the problem is that I get this error message?
(I attach a screenshot on the link below also from Visual Studio 2019 Preview .NET Core 3.1)
Image of the error in C# code behind in Visual Studio 2019 Preview
First, you can ensure SQL Server Express is installed and working by the following steps
Open Visual Studio Installer >> Modify
Expand .Net desktop development
Scroll down and check SQL Server Express is installed or not
[
if it is installed go to step 2
Open Server Explorer
Connect to Database
Choose Data Source >> Microsoft SQL Server Database File
Add Connection >> Browse to your database file, and make sure to Test Connection, then OK
After that, inside Server Explorer will display the connections, right click on that >> properties
Then you can get the Connection String
Second, with Connection String got above, you can check it work or not by
SqlConnection cnn = new SqlConnection(**connectionString**);
cnn.Open();
// not do anything yet
cnn.Close();
Then run to make sure you can open the connection to the database
UPDATE :
Check which Stored Procedures you want is existed or not?
I am attempting to connect to a local SQL Server database in C#.
I am currently using the following connection string:
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\majorWork\majorWork\gameStats.mdf;Integrated Security=True";
However, I do not want to use a hardcoded file path, as I wish to be able to use the application across multiple computers, where the file path will be different. How should I go about doing this?
Best way is set this connection in Web.Config file.
<Database>
<ConnectionString name="connection">Server=servername; Initial Catalog=dbname; Persist Security Info=False; User ID=username; Password=password; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False; Connection Timeout=30;;</ConnectionString>
</Database>
Then add Add System.Configuration as a reference.
in C# you can call this
string constring = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
After that you can create new connection instance by passing this to
SqlConnection con = new SqlConnection(constring)
If u install SQL server express using the default instance, then you can connect using . as your server name anyone can use it with default instance as well.
1.then in visual studio, click on solution explorer
2. Connect database, follow the instruction for SQL server
3. When it gets to server name use . to connect and choose your database name which you have created already in ms SQl, then test your connection
4. After it successful, u can now click on the database name showing under solution explorer,
5.after u click the database name, at the button right corner, there will be a connection string, copy it and use
This will be declared publicly or globally
Sqlconnection con = new sqlconnection("paste the connection string");
And to use
Sqlcommand cmd = new sqlcommand("insert into......",con);
Con.open ();
Cmd.executenonquery();
Con.close();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
TL;DR so you stop putting this on hold:
Visual Studio will not allow me to create a live connection to a database on an SQL server within a project, even though it can communicate with the server outside of projects. I want it to have a live connection so I can make a website that uses and allows access to the database.
I have Visual Studio 2017 Professional, and Microsoft SQL Server Management Studio 2017.
I have successfully connected a database from the server to Visual Studio such that I can edit the database in Visual Studio, and the server will reflect my changes. However, I cannot get a live connection to the server inside any project. When I import the database into a project, it just creates a copy that does not actually communicate with the server.
I'm thinking I need to create some sort of special object or change some settings in Visual Studio.
Do I need to switch to Enterprise for supported features? It seems rational that the professional edition should be sufficient for this, but if anyone knows how to solve this kind of issue with a different version of Visual Studio or how to create a website connected to a database server through another [hopefully affordable] program, I'm all ears. Thank you!
(This paragraph added later for clarity:) My goal is to create a website using Visual Studio which allows authorized users to edit the database. Unless doing so is a terrible idea, I want to start by making it possible to edit the database on the server using the website made in Visual Studio, and then add the security features. The current database on the server is placeholding junk until the system is satisfactorily set up. It sounds like it may be possible access the database using a website without directly putting it in the Visual Studio project, so I'm looking into the directions provided in the second comment.
The least error-filled solution I managed is as follows, based on #Symon's comment and link. I've tried several things for the first line, and being public void seems to case about 1/30th the errors as being anything else I've tried, which definitely doesn't mean it's actually the right answer. Items in square brackets are removed for security reasons. I entered the credentials for the database exactly as I did in the popup window to connect Visual Studio in general to the database on the server.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public void heresanamespacethingy (string stp)
{
//GET STORED PROCEDURE HERE
string conStr = #"Data Source=[server name]; Initial Catalog=[database name]; User ID=[my user ID]; Password=[my password]";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
The error is
CS0116 A namespace cannot directly contain members such as fields or methods.
I'm using VS Community and can interact with my MS SQL Server just fine. The edition of Visual Studio that you are using isn't going to limit what you can do code-wise. The editions merely add extra features. I have never heard of anyone being limited in their projects because of the edition of Visual Studios that they are using.
As #Kfirprods stated, it may be very helpful for you to manage your Server/Databases with Microsoft SQL Server Management Studio 2017 instead of trying to use Visual Studios for everything.
The most common way that I've seen to get your live/current database information and data is to have your C# code call to the live data and pull it. I will have an example of C# calling a stored procedure below. The example only calls a stored procedure, showing how it is possible for you to use C# to connect to SQL Server and alter data. You can also send individual, inline queries through this method. Though, to avoid SQL injection (especially since it's a website) , it'd be better protection to use this method to call Stored Procedures and Views rather than sending inline queries.
This may be a good link to read up on for learning how to start using C# to connect to SQL Server. It's what I used to get started!
I have my SQL Server Management studio connected to my Server/Databases, and my Visual Studio is only concerned about my C# code. It helps keep things separated and organized (for me, anyway).
Here is a sample of a C# method that connects to a SQL Database, and runs a Stored Procedure:
public void CallSproc(string stp)
{
//GET STORED PROCEDURE HERE
string conStr = "Data Source=" + ConfigurationManager.AppSettings["DataSource"] + "Initial Catalog=" + ConfigurationManager.AppSettings["InitialCatalog"] + "Integrated Security=True;";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
Code Explained:
ConfigurationManager.AppSettings[] points to my App.config file and keys (identifiers) where this data is stored. In case the current server is lost, the program doesn't require a re-compile. The config file just needs altered to point to the right location.
The variable stp is a string that is passed from another method which holds the name of the stored procedure (ex. "stpAddNumbers").
conStr is the connection string that tells the SqlConnection() call what Server and database to connect to.
conn.Open(); opens the connection to the SQL Server itself.
cmd.CommandType = CommandType.StoredProcedure; tells the code that you're calling for a stored procedure.
cmd.ExecuteNonQuery(); executes the stored procedure and the results are returned.
CS0116 A namespace cannot directly contain members such as fields or methods:
With the code you have shown along with the error message, you don't seem to have a namespace at all. To fix this, simply wrap your method in a namespace. Like so:
...
using System.Threading.Tasks;
namespace HeresANameSpace
{
class ThisIsAClass
{
public void HeresAMethod (string stp)
{
//GET STORED PROCEDURE HERE
string conStr = #"Data Source=[server name]; Initial Catalog=[database name]; User ID=[my user ID]; Password=[my password]";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
//End of HeresAMethod()
}
//End of HeresAClass
}
//End of HeresANamespace
}
When starting from a blank Code file, you need to write in the namespace , classs and methods . A method goes inside of a class, a class goes inside of a namespace.
I'm working on a Windows CE application, and I need to copy server table data to SQL Server CE database (local) using C# programming. I'm using Visual Studio 2008, SQL Server 2008 for the development.
Below is the code I'm working with, but it seems in VS2008 SqlBulkCopy isn't supported. Do we have any alternatives to achieve this functionality?
SqlConnection source = new SqlConnection(Con_s);// server connection string SQL Server
SqlCeConnection destination = new SqlConnection(Con_l);// Local connection string SQL Server CE DB
SqlCeCommand cmd = new SqlCeCommand("DELETE FROM ProductList", destination);
source.Open();
destination.Open();
cmd.ExecuteNonQuery();
cmd = new SqlCommand("SELECT * FROM Products", source);
SqlDataReader reader = cmd.ExecuteReader();
SqlBulkCopy bulkData = new SqlBulkCopy(destination);
bulkData.DestinationTableName = "ProductList";
bulkData.WriteToServer(reader);
bulkData.Close();
destination.Close();
source.Close();
Add: I have included both using System.Data.SqlClient; & using System.Data; in the code
Since I cannot paste image in the comments,I am including it as answer.
SqlBulkcopy is present under System.Data.SqlClient namespace.
Just navigate to SqlBulkcopy namespace,you must get navigated to the below
If not I think your dll is corrupted may be you need to reload new one.
This is my connection string
SqlConnection conn = new SqlConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
I copied it from the property, I added # in front but didn't change anything. There are no errors during Build and Run. But when I click insert button, the below error shows up.
"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. "
I tried editing connection string and using datadirectory instead of the entire path, but the same error occurs, I am new to .net so I am unable to figure out what could be the cause. I tried google but I can't tell whether the solutions there are related to my problem.
Thanks in advance!
You're using the wrong type of SQL connection. You should be using the SqlCeConnection class:
SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
Here is a really good reference for SQL CE connection strings.
The data source for SQL Server is a machine name, not a file name.
You should add a reference to the SQL CE assembly, and do this:
SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
For MSSQL Server Compact Edition, you should use the SqlCeConnection class.
So this should work:
SqlCeConnection sqlConnection = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
Create you connection string as follow :
add in the namespace using System.Data.SqlServerCe;
SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual
studio 2010\Projects\WFA1\WFA1\database.sdf; Persist Security Info=False;");
if .sdf file inside you project then you can use :
string strConnectionString ="Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.
GetExecutingAssembly().GetName().CodeBase) + "\\database.sdf;Persist Security Info=False;";
SqlCeConnectionconn = new SqlCeConnection(strConnectionString );