Hi @Roberto C , Welcome to Microsoft Q&A,
Using C# to connect to a remote SQL Server database can be achieved through the SqlConnection
class.
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Connection string
string connectionString = "Server=your_server_address;Database=your_database_name;User Id=your_username;Password=your_password;";
// Create a connection object
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
// Open the connection
connection.Open();
Console.WriteLine("Connection successful!");
// Create an SQL command
string query = "SELECT * FROM YourTableName";
SqlCommand command = new SqlCommand(query, connection);
// Execute the command and read the data
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"{reader["ColumnName"]}");
}
}
}
catch (SqlException ex)
{
Console.WriteLine("Database operation error: " + ex.Message);
}
finally
{
// Ensure the connection is closed
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
}
}
When using SQL commands, try to use parameterized queries to prevent SQL injection attacks. For example:
string query = "SELECT * FROM YourTableName WHERE ColumnName = @value";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@value", someValue);
Make sure the firewall on the server where the remote SQL Server resides is configured to allow connections from your client IP address. By default, SQL Server uses TCP port 1433.
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.