Sql connection string via SqlClient - c#

I have an issue trying to manually connect to a sql server on my network.
I have a web API with a conn string that works fine, I have a VS2015 winforms project i set up to test the conn using the VS tool to connect, this also works fine.
However when i try to connect via SQLconnection it fails and says the server cannot be found or isnt accessable.
So heres the test code...
string connectionString = #"Data Source=test1\test1;Initial Catalog=my_test;Integrated Security=True;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand("", connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
Now i dont really care about results or anything i simply need to establish a connection. I cant figure out why it throws this error, when my Web API works and the VS tool for connection to DBs works fine too.
I have checked the server and enabled named pipes too just to make sure.
Any ideas?
EDIT:The error i catch...
{"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)"}
happens after about 15 seconds trying to open the connection.
The thing is this connectiin string i tried is the exact same string used via the SQL tool, I did this so i knew i had a valid string.
ODBC connection also falls over with the same message.
I checked from my machinbe is i can listen to port 1433 but it says the server isnt listening.
However looking at the server its set to dynamic ports with a range of any to 41934, so im at a loss as to why it says its not listening evenb though its to dynamic ports
EDIT2: Well, must be permissions or drivers... just tried the exact same code and worked instantly...
This is diving into the realm of the unknown i feel. might ask for deletion of the question if no solution is found

I think that i see the problem:
string connectionString = #"Data Source=test1\test1;Initial Catalog=my_test;Integrated Security=True;";
Integrated Security is used for local logins, You could make an account in the database and change the connection string to:
string connectionString = #"Data Source=test1\test1;Initial Catalog=my_test;User id=<Username>;Password=<Password>;";
I hope this helps!

Related

Access Wamp Mysql from extenral application

I have this code snippet where I am trying to make a connection with a remote database, located on LAN Ip with wamp.
string myConnectionString = "server=192.9.210.62;port=8088;database=testDB;uid=root;pwd=;";
MySqlConnection con = new MySqlConnection(myConnectionString);
con.Open();
MessageBox.Show("connection open");
con.Close();
But it is failing due to socket exception. here are the error
MySql.Data.MySqlClient.MySqlException: 'Reading from the stream has
failed.'
Then, I search for this problem, and it seems that I have to allow a remote connection to my SQL. But remember I have already put my server online already. There is also bind-address setting that need to be set 0.0.0.0 but i am unable to find it in .ini file.

:'Unable to connect to any of the specified MySQL hosts.' error

I want to connect to a MySQl db using a connection string but unable to connect
I'm using UWP and using The fall creator version for both target and min version
I've installed the Nuget packages for Mysql connector
I've tried to change the string with and without port,ect.
public string GetMatchCode()
{
string connectString = "Server=###.###.###.###;Database=Db;Uid=root;Pwd=123;sslmode=none;port=3306";
string sql = "SELECT * FROM `customer`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
MySql.Data.MySqlClient.MySqlException: 'Unable to connect to any of the specified MySQL hosts.'
MySqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The error starts at connect.Open();
I've tested the connection with workbench to make sure it's working.
I've looked through most similar post but none have worked for me.
There could many possible scenario's where connection will fail.
Please see below points to troubleshoot your error.
Check your Windows Firewall to ensure that server has an access to Port's associated with your MySql.
Disconnect and re-connect your VPN client.
Follow standard Spacing and Order of parameters in connection string. Follow below format to build/form connection string.
Server=ServerAddress; Port=4563; Database=DataBaseName; Uid=UserName;
Pwd=Password;
Consider using Connection Pulling, So existing connection will be reused.

Can I add an SSIS script block with custom script into the toolbox?

I have a common SSIS C# script task block that we use in our company. It is only a single script block but the script inside is always the same. We use it in lots of our SSIS packages. It is kind of a pain to always have to copy the block from another project or copy the script from somewhere into a new script block.
Is there any way I can put a copy of that script block with the prewritten script into the SSIS Toolbox so I can just drag-and-drop it into our projects?
EDIT:
OK, so I have started writing a custom control based on the advice given below. I've got everything working except for connecting to my SQL Server database. Using the following code:
SqlConnection SettingsConnection = (SqlConnection)_selectedConnectionManagerSource.AcquireConnection(transaction); // Errors here
SqlCommand sp_GetAllValues = new SqlCommand();
sp_GetAllValues.Connection = SettingsConnection;
sp_GetAllValues.CommandType = CommandType.StoredProcedure;
sp_GetAllValues.CommandText = "Get_My_Data_For_Project";
sp_GetAllValues.Parameters.AddWithValue("#project_name", pkgname);
SettingsConnection.Open();
SqlDataReader SettingsReader = sp_GetAllValues.ExecuteReader();
while (SettingsReader.Read())
{
I get this error message:
[Connection manager "DevServer"] Error: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available. Source: "Microsoft SQL Server Native Client 11.0" Hresult: 0x80004005 Description: "Login timeout expired".
An OLE DB record is available. Source: "Microsoft SQL Server Native Client 11.0" Hresult: 0x80004005 Description: "A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.".
An OLE DB record is available. Source: "Microsoft SQL Server Native Client 11.0" Hresult: 0x80004005 Description: "Named Pipes Provider: Could not open a connection to SQL Server [53]. ".
What am I doing wrong?
ANOTHER EDIT:
If I change the code to:
string myConnectionStr = _selectedConnectionManagerSource.ConnectionString;
SqlConnection SettingsConnection = new SqlConnection(myConnectionStr);
SqlCommand sp_GetAllValues = new SqlCommand();
sp_GetAllValues.Connection = SettingsConnection;
sp_GetAllValues.CommandType = CommandType.StoredProcedure;
I get this error message:
Error: The Execute method on the task returned error code 0x80070057 (Keyword not supported: 'provider'.). The Execute method must succeed, and indicate the result using an "out" parameter.
If I take out the 'provider' section of the connection string (hard code the string):
string myConnectionStr;
myConnectionStr = "Data Source=mydatabase;Initial Catalog=mycatalog;Integrated Security=SSPI;";
SqlConnection SettingsConnection = new SqlConnection(myConnectionStr);
SqlCommand sp_GetAllValues = new SqlCommand();
sp_GetAllValues.Connection = SettingsConnection;
sp_GetAllValues.CommandType = CommandType.StoredProcedure;
I get this error message:
Error: The Execute method on the task returned error code 0x80131904 (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)). The Execute method must succeed, and indicate the result using an "out" parameter.
This last block is exactly the code I was using in my Script Task block and it is working fine. I'm just not sure what the difference between the two... :/
FINAL EDIT:
All of these error messages were because my test package was set to run 64-bit instead of 32-bit. I changed the package to run 32-bit and it started working with an ADO.NET connection. My final code looks like this:
string myConnectionStr = _selectedConnectionManagerSource.ConnectionString;
SqlConnection SettingsConnection = new SqlConnection(myConnectionStr);
SqlCommand sp_GetAllValues = new SqlCommand();
sp_GetAllValues.Connection = SettingsConnection;
sp_GetAllValues.CommandType = CommandType.StoredProcedure;
and it works great as long as it is using an ADO.NET data source. It still would not work with an OleDb data source even using OleDbConnection, etc. Not sure why. But, now that it is working with ADO.NET, I really don't care to solve that one.
Now that the base functionality is working fine, I'm off to write the UI... :)
The only way is to create custom task of it: http://microsoft-ssis.blogspot.com/2013/06/create-your-own-custom-task.html
An alternative is to create a custom assembly and reference that in your Script Task: http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html
So I think you ran into a snag involving your connection's provider:
You can't include the provider keyword in a SqlConnection connection string. All of the connections in SSIS are OLE DB connections which include the provider keyword in its connection string.
So in your code you should be using an OleDbConnection instead of a SqlConnection (and OleDbCommand, OleDbDataReader, etc.)
For your hardcoded connection string, does your server instance name happen to have a slash in it, by any chance? This tripped me up once, you have to escape slashes in C# strings, so if your connection string is
Data Source=SERVER\INSTANCE;Initial Catalog=DatabaseName;Integrated Security=SSPI;
Your C# code should look like so:
string ConnStr = "Data Source=SERVER\\INSTANCE;Initial Catalog=DatabaseName;Integrated Security=SSPI;";
or (my preference)
string ConnStr = #"Data Source=SERVER\INSTANCE;Initial Catalog=DatabaseName;Integrated Security=SSPI;";

windows Application Database Connection c#

Im facing problem with database connection on windows Application Database Connection c#... here is my connection ,,, PC2 is PCNAme
private static SqlConnection con = new SqlConnection(
"Data Source=PC2\\SQLEXPRESS; Initial Catalog=Database1;Integrated Security=True"
);
when I run the form I get this unhandled exception on con.Open();
sqlException was unhandeled:
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)
hope some one can help Im trying to solve it for many hours but not working.
Check this trouble shoot steps on MSDN:
The SQL Server client cannot connect to the server MSDN
And much better if you separate your connection string to your ado.net sql connection.
private const string _thisConnectionString = "Data Source=PC2\\SQLEXPRESS; Initial Catalog=Database1;Integrated Security=SSPI";
Use the "Using" Statement ensure that you always close your Connection.
Best Practices for Using ADO.NET MSDN
using (var conn = new SqlConnection(_thisConnectionString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "Your SQL Query STuff";
conn.Open();
}
Regards
Try This:
private static SqlConnection con = new SqlConnection(
"Data Source=PC2\SQLEXPRESS; Initial Catalog=Database1;Integrated Security=True"
);
Go to SQL Server Configuration Management -> Click on SQL Server Services
Verify SQL Server and SQL Server browser both are running. you can see a Greed play button there. if it's not running right click on the service which shows Red, go to properties, Click Built in Account and Press Apply then OK, There try to start by right click.

Exception with connection in ADO.NET

I am trying to learn ADO.NET to connect with SQL Server ...
I install SQL Server with Visual Studio ....
there is data base called "Northwind" as example with it ...
I am trying to read this database , I wrote this code ...
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataSetReaderFromSQL
{
class Program
{
static void Main(string[] args)
{
SqlConnection connection = new SqlConnection(#"Data Source=(local);Integrated Security=SSPI;" + "Initial Catalog=Northwind");
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "Select CustomerID , CompanyName from Customers";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
Console.WriteLine(reader["CustomerID"] +""+ reader["CompanyName"]);
reader.Close();
connection.Close();
}
}
}
When the application runs, it's take a little of time then throw exception when it trys to open connection ...
the text of the exception :
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)
I am using Windows 7 as my operating system, and I put username on my account ...
I am sure that SQL Server was installed on my computer
where is my error ??
Either
You haven't configured Sql Server to allow remote connections, as the error message tells you =)
Your datasource is wrong. Try .\SqlExpress or just . Ordinarily when Visual Studio installs Sql Server Express, it installs it as a named instance called SqlExpress.
Visual Studio includes Express edition of SQL Server. Thus, your connection string should most likely look like "Data Source=(local)\sqlexpress;...".
If you want a quick & easy way to try different connection strings, I suggest DatabaseTester (disclaimer - I wrote it). It's free and a very easy way to test. Also, for figuring out connections strings ConnectionStrings.com is your best friend.

Categories

Resources