Could not open a connection to SQL Server 2012 - c#

Hy,
I am using SQL Server 2012 under MS Visual Studio 2012.
Below is my connection string from app.config
<add key="Platform" value="Data Source=Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>
and my connection class
static SqlConnection con;
public static SqlConnection GetConnection()
{
con = new SqlConnection(ConfigurationManager.AppSettings["Platform"].ToString());
return con;
}
internal void AddCustomer (Buyer customer, User user, PlatformType type )
{
SqlConnection conn = DALConnection.GetConnection();
try
{
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
...
con.Open();
cmd.ExecuteNonQuery();
My database is stored under my project folder.
The error I get when I try to use my method is:
Could not open a connection to SQL Server 2012
Sincerely,

Your connection object is wrong, you are passing conn in Command while for Connection open you are using con object not conn:
con.Open();
use :
conn.Open();
you code will be like:
try
{
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
}

Although your code has some issues, It seems that it should work.
Try testing your connection string using an independent tool for connectivity.
For testing the connection string take a look at this SO thread.
As #hvd has mentioned in one of the comments, your code is confusing as you have con which is equivalent to conn. this makes your code hard to follow. I recommend you refactor it so it will be easier for you (and others) to follow.
Good luck!

Try this:
<add key="Platform" value="Data Source=.\Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>

If your SQL Server is on a different machine than your Visual Studio or app, are the required ports open in the Windows Firewall ?
Try these steps:
http://blog.sujay.sarma.in/2013/12/19/SCRIPT-Open-ports-in-Windows-Firewall-for-SQL-Server-connectivity

Related

OleDB connection string for SQL Server in a C# program

I have seen lots of answers to connect to MS Access via OleDB but there is not good answer for SQL Server. I try to connect to a SQL Server database via OleDB provider in my C# program.
This is the connection string I am providing.
Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI
But it gives me error
‘Keyword not support ‘Provider’’
What I want to do here is connect database via OleDB in C# program.
This works as expected on my side. From the error message I strongly suspect that you are using the SqlConnection class instead of the OleDbConnection (Of course you need to use all the other classes provided by OleDb like OleDbCommand, OleDbDataReader etc...)
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(OleDbConnection cnn = new OleDbConnection(connStr))
{
....
}
When in doubt, use the string builder in visual studio. That way unsupported keywords can't creep into your connection strings, the following is a wonderful example on how to use it.
http://www.c-sharpcorner.com/uploadfile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/
The same Connection string is working fine at my end.
I am posting my sample code which is executes successfully at my end
public string connStr = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=<dbName>;Integrated Security=SSPI";
public OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
public void Test()
{
con = new OleDbConnection(connStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from tblApartments", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
Please place breakpoint and check line to line and when your breakpoint comes to con.close(); then check ds, you can see the output.
The connection string you're using, considering the OLE DB provider, is correct. I didn't find any error in the connection string used, if you want to connect to a SQL Server data source.
Most probably, the reason of that error should be that you're not using correctly all the classes and objects required by the OLE DB provider, like OleDbCommand (that is similar to a SqlCommand but it's different), OleDbConnection, OleDbDataAdapter and so on. In a nutshell, the reason of that error should be this:
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(SqlConnection scn = new SqlConnection(connStr))
{
....
}
Indeed, using a SqlConnection object, the ConnectionString property doesn't support the keyword Provider and, executing your application, you got an error about a keyword not supported.
Have a look at this simple tutorial about the use of OLE DB provider.

Why LinqPad can connect the Db while my console app. throws an SQL Exception for the same code?

I run the code below
var connectionString="Data Source=MyFooServer.myDomaion.com;Initial Catalog=FooDb;Integrated Security=True; MultipleActiveResultSets=true";
using (var con = new SqlConnection(connectionString))
{
var q = "SELECT COUNT(*) FROM Pizza";
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = q;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
reader = cmd.ExecuteReader();
con.Close();
}
from 2 different places:
1) LinqPad
2) A Console application in Visual Studio 2010
LinqPad works fine. No exceptions.
But the same code throws an SQL exception: "The target principal name is incorrect. Cannot generate SSPI context."
QUESTION: Why I can connect to my database without any problem from LinqPad but not from the console application even tough I run the same code?
Rebooting my machine helped... No idea what was the root cause of this behavior tough.
Try to use SQL username and password instead of Windows Inegrated Security.
var connctionString="Data Source=MyFooServer.myDomain.com;Initial Catalog=FooDb;Uid=Username; pwd=password"

Inserting data into sql server fails with no reason

I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)

Error While Adding DataSource in Data Connections

When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}
The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

Problems connecting to .sdf database through SqlConnection/SqlCeConnection

I'm having immense trouble getting a connection to a .sdf (sql compact edition) database. I can connect initially to extract rows in order to verify a username/password, but when I try to add items to the database, either by a SqlCeConnection/SqlCeCommand command or by trying to add items SqlClient/SqlCommand connection, I have no luck. I get:
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)
when using:
private void button1_Click_1(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
or when I try:
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
Nothing happens, it seems to work until I check the .sdf file and see nothing has been added. I do not have SQL Server CE installed, though I do have 2008 R2 installed (I'm working on someone else's project).
Right now I'm not worried about the security holes, I'm just trying to successfully add a record. Any help would be much appreciated, as I've spent about three or four hours working on something I figure would take about 20 minutes.
Probably you have found the solution by now, but if you use a sdf file, the assembly you should add a reference to System.Data.SqlServerCe and then something like:
SqlCeConnection sqlConnection1= new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf";
System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
you most to use sqlceconnection and sqlcecommand classes. like this :
SqlCeConnection conn = new SqlCeConnection(connectionString);
SqlCeCommand cmd = conn.CreateCommand();
conn.Open();

Categories