Exception when trying to connect to .sdf database - c#

I have database in file C:\Users\Pawel\Documents\DB.sdf. How can I connect to it?
Simple code below does not work and generates exception.
Code:
[WebMethod]
public String TestCon()
{
SqlConnection sql = new System.Data.SqlClient.SqlConnection(
#"Data Source=C:\Users\Pawel\Documents\DB.sdf");
string str = "OK";
try
{
sql.Open();
sql.Close();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
Result:
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
What am I missing? What I should do to open connection correctly?
EDIT:
System.NotSupportedException: SQL Server Compact is not intended for ASP.NET development.
Great :P

Consider using System.Data.SqlServerCe.SqlCeConnection:
System.Data.SqlServerCe.SqlCeConnection con =
new System.Data.SqlServerCe.SqlCeConnection(#"Data Source=C:\Users\Pawel\Documents\DB.sdf");
(Add a reference to System.Data.SqlServerCe, if necessary)
Also, to use it with ASP.NET, add:
AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);

Apparently, you are using a SQL Compact Edition (sdf file). Have you tried using SqlCeConnection instead of SqlConnection ?
As a bonus: if you dont want to mess with connectionstrings anymore, please try this.
Do do so, you have to add a reference to System.Data.SqlServerCe assembly.

Related

How can I make the SQL connect in a Windows Form?

I'm still working on my messenger programme, it will be more secure but I'm just testing stuff. I've got a login form which is meant to connect to the SQL database, I've set it up now with a local SQL as I was trying to get it working (it still doesn't work) and I was just wondering what I did wrong.
private void button1_Click(object sender, EventArgs e)
{
LoginInfo.un = textBox1.Text;
LoginInfo.pw = textBox2.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost:3306; User Id=PXgamer;Password=Password1; Initial Catalog=login;";
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show("Error with the database connection");
}
string qry1 = "Select * from login where Password=#Password and Username=#Username";
SqlCommand com = new SqlCommand(qry1, con);
com.Parameters.AddWithValue("#Username", LoginInfo.un);
com.Parameters.AddWithValue("#Password", LoginInfo.pw);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Login Successful", "Login Information");
}
}
if (dr.HasRows == false)
{
MessageBox.Show("Access Denied", "Login Information");
}
this.Hide();
var frmMain = new frmMain();
frmMain.Closed += (s, args) => this.Close();
frmMain.Show();
}
So that's my code, the connection hangs at first, and then the "Error with the database connection" error appears. I tried looking that up, but it says it's when the connection hasn't opened. So obviously I'm guessing it's something wrong with the connection string.
In debugging, this is the part that gets highlighted:
SqlDataReader dr = com.ExecuteReader();
This is the error shown:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Error without the catch:
Additional information: 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)
You are trying to connect to a MySQL database using SQL Server-specific ADO.NET classes. That won't work.
You can see that your current code is trying to connect to a SQL Server instance from the error message that you got:
Additional information: 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)
You need to download the MySQL-specific drivers to connect to MySQL, and use that instead.
ADO.NET driver for MySQL
Losing the port (:3306) from your connection string should work fine. If the SQL Server is not on default port, specify as below (using a comma, not a colon)
Data Source=server.ip.address,1433; Initial Catalog=myDataBase;
User ID=myUsername; Password=myPassword;
Check this link for other variations of SQL Server connection strings
Every line of code that need the 'con' object to work should stay inside the 'try' block of your method.
Also, if you can't open the connection, there are two possibilities:
your connection string is wrong;
your local SQL Server doesn't accept a connection from your application (misconfigured, not running, etc);
both;
You can have a look here for connection strings for SQL Server: https://www.connectionstrings.com/sql-server-2008/
Finally... use a 'finally' block at the end for 'con.Close()'.

C# - Can't connect to remote MySQL server

My problem is that I can't connect to my website remote MySQL server. I have read all answers in stackoverflow.com, but I can't find right answer. Here's my C# code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
SqlConnection con;
string connectionString = #"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";
con = new SqlConnection(connectionString);
try
{
con.Open();
Console.WriteLine ("Connection Open ! ");
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
Console.WriteLine(ex.Message); //shows what error actually occurs
}
Console.ReadLine();
}
}
}
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)
Any ideas?
When connecting to a MySQL-Database I always used the MySQL Connector you can get here: https://dev.mysql.com/downloads/connector/net/6.9.html
You have to import the MySQL namespaces to your project and then you can use the MySQLConnection instead of the SQLConnection that is, as far as I know, only for MSSQL servers.
http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp
try the following
string connectionString = #"Server=[IP adress]:3306;Database=[database];Uid=[user];Pwd=[pass];";
instead of
string connectionString = #"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";

Sybase ODBC Driver Client unable to establish connection

I am trying to hit a remote Sybase database using ODBC. I have written a C# program with the following code
try
{
String conString = "Driver={Adaptive Server Enterprise};server=ipAddress;port=portNumber;db=databaseName;uid=strUserName;pwd=strPassword";
con = new OdbcConnection(conString);
con.Open();
}
catch (Exception exp)
{
con = null;
}
After the connection times out ,the exception message says :-
ERROR [08001] [Sybase][ODBC Driver]Client unable to establish a connection
On Debugging the code when I hover on "con.Open()", the ServerVersion attribute of the connection object displays the following message 'con.ServerVersion' threw an exception type 'System.InvalidOperationException'
Can anybody help me in finding out the reason for this exception..?
I would double check first that you can connect via a normal SQL client (e.g. isql, Aqua etc) on the same hostname and port.
However that looks from a quick google like a possible Sybase Adaptive Anywhere (as opposed to Enterprise) error so are you using the right driver for the type of database? They are two different products.

Connection to SQL Server Database inside Visual Studio 2012 C#

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

Connecting C# to SQL Server Compact database

Hi I'm trying to connect an SQL server compact database to my program and I want a button that deletes all entries from the database, when I Press said button the program throws an exception and gives the following error message "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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
Help Please? =]
Sorry, Code is Below =]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
namespace Booking_system_Final
{
public partial class PendingJobs : Form
{
SqlConnection sc = new SqlConnection("Data Source=C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf");
public PendingJobs()
{
InitializeComponent();
}
private void PendingJobs_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bMSDataSet.Bookings' table. You can move, or remove it, as needed.
this.bookingsTableAdapter.Fill(this.bMSDataSet.Bookings);
// TODO: This line of code loads data into the 'bMS_DataDataSet1.Bookings' table. You can move, or remove it, as needed.
}
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM Bookings");
cmd.Connection = sc;
cmd.ExecuteNonQuery();
sc.Close();
MessageBox.Show("Database Cleared");
}
}
}
Try use SqlCeConnection class rather than SqlConnection:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf;Persist Security Info=False";
If you want to connect to SQL Server Compact, use SqlCeConnection, SqlCeCommand etc. Add a reference to the SQL Server Compact ADO.NET provider, System.Data.SqlServerCe.dll
Have a look at this blog article: SQL SERVER – FIX : ERROR : (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server)
This goes step-by-step through what you might need to do:
In short:
SQL Server should be up and running.
Enable TCP/IP in SQL Server Configuration
Open Port in Windows Firewall
Enable Remote Connection
Enable SQL Server Browser Service
Create exception of sqlbrowser.exe in Firewall
Recreate Alias
About the where and what to do in each step, you will find more in-depth information in the article.
You may also want to have a look at the Connection strings for SQL Server Compact. There you can find other variations of the connection string you could try to play with.
You seems to be using a bad connection string. (Or the file path is wrong). Check out http://www.connectionstrings.com/sql-server-ce for connection string options.

Categories