c# windows, local database(sql server), connection string not working properly - c#

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 );

Related

Insert data to a SQL database in .NET Core 3.1 using C# receives an error

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?

Connect to a SQL Server database without a set file path

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();

Connection string error - Sql Express

I am trying to connect to my local database(Sql Express) in Visual Studio to the Application Forms button. In Server Explorer and properties, connection string is:
connectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Work\Documents\Visual Studio 2015\Projects\MyTest\MyTest\Database.mdf";Integrated Security=True;Connect Timeout=30";
All the guides I've been reading use following connection string:
connectionString = "Data Source=localhost\\SQLExpress;Initial Catalog=Databasen;User ID=admin;Password=password";
But when inserting this string path in my button in Form1, and press button, an error appears - couldn't open connectionSystem.Data.SqlClient.SqlException (0x80131904):
Could someone explain the difference and which one of them should be used and why? And how i'm able to use the last connection example.
The top one is for a SQL data file connect that's located here: C:\Users\Work\Documents\Visual Studio 2015\Projects\MyTest\MyTest\Database.mdf
connectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Work\Documents\Visual Studio 2015\Projects\MyTest\MyTest\Database.mdf";Integrated Security=True;Connect Timeout=30";
The second is to a local database. Make sure the name of the sever "localhost" is correct. Also I noticed in your database name you have 'Databasen' is this correct spelling. Check user name and password too.
connectionString = "Data Source=localhost\\SQLExpress;Initial Catalog=Databasen;User ID=admin;Password=password";
Please explain what you are doing when you say
But when inserting this string path in my button in Form1, and press button, an error appears - couldn't open connectionSystem.Data.SqlClient.SqlException (0x80131904)
You should never put the connection string in your user interface.
If you need to know how to connect through code we can show you.

Connection string using SQL Server authentication in C#

I am creating an Excel file in C# with SQL Server. I've tried several connection strings, but it keeps saying that it does not recognise my user ID (the ID is valid and can connect directly to SQL with this)
Can you help me, or tell me where is the error that comment?
Below I show the connections I've tried
connectionstring = "Integrated Security = SSPI;Initial Catalog='DATABASENAME'; Data Source=XXX.XXX.X.XX; ";
connectionstring = "SERVER=XXX.XXX.X.XX;DATABASE=DATABASENAME;UID=sa;PASSWORD=pass;";
connectionstring = "Persist Security Info=False;User ID=sa;Password=pass;Initial Catalog=DATABASENAME;Server=XXX.XXX.X.XX";
connectionstring = "Data Source=192.168.0.18;Initial Catalog=DATABASENAME;Persist Security Info=True;User ID=sa;Password=pass";
connectionstring = "Persist Security Info=False;Integrated Security=true;Initial Catalog=DATABASENAME;server=(XXX.XXX.X.XX)";
connectionstring = "Data Source=XXX.XXX.X.XX,1433;Network Library=DBMSSOCN; Initial Catalog=DATABASENAME;User ID=sa;Password=pass";
cnn = new SqlConnection(connectionstring);
Here is the sample connection string format
Data Source=[server];Initial Catalog=[databasename];User ID=[sa];Password=[password]
example - named instance
Data Source=localhost;Initial Catalog=master;User ID=sa;Password=sa123
in case of the default instance
Data Source=localhost\sqlexpress;Initial Catalog=master;User ID=sa;Password=sa123
if you are trying to access express version from another machine please refer and replace localhost with ip or machine name.
Navigate to C:\Windows\System32\odbcad32.exe. Go to the Drivers tab and then check to see which ODBC drivers you have installed on your system.
Then go to this website and follow the links at the top for whichever ODBC driver you have installed on your system. For C# you may or may not need the Driver= buts its usually safe.
This is the connection string which usually works for me in C# asp.net, however:
Server=[SERVER];Database=[DATABASE];Uid=[USER];Pwd=[PASSWORD]
(note how it is different than yours: Pwd= as opposed to Password=)
"HP\\ADMIN;Initial Catalog = PAY_PROCESSING_GO; User ID=sa; Password=admin#123"
this is my connection string but connection consist Keywords. How to solve this problem

OleDbConnection with MsAccess using C#

I'm trying to connect ms access database using c#. While doing that I'm stuck at one place.
Whenever i try to open the connection using
OleDbConnection conn = new OleDbConnection("connection string valid");
conn.Open();
I get error that whichever is the provider, it is not registered onto the local machine !
I have downloaded the msaccessEngine also from well known link http://www.microsoft.com/en-us/download/details.aspx?id=13255.

Categories