How to connect to remote SQL Server database using Visual C#? - c#

I am creating a Windows forms application and my SQL Server database is on a remote server. How can I connect to it using Visual C# and ADO.NET?

You need to investigate the SqlConnection, SqlCommand and possible SqlDataReader and SqlDataAdapter components in .NET (see the MSDN online docs).
Once you have that, you need to define your connection string - check that site link for a huge selection and explanation of connection strings.
Then you basically connect using:
using(SqlConnection conn = new SqlConnection('your connection string here'))
{
conn.Open();
// do stuff
conn.Close();
}
and you can do stuff in various ways, e.g. by filling data sets, reading values etc.
Read the MSDN ADO.NET Overview to get started! Or Google for "ADO.NET tutorial" - you'll find tons of links.

The answer can be found here -
Connect to remote MySQL database with Visual C#
Also, read up and download from here -
http://dev.mysql.com/downloads/connector/net/5.2.html

In the eye of MS SQL Server it is no difference where your SQL Server is located. All you need is to make sure you have access that server in terms of IP and Port number.

Use the below code to create the connection objects necessary.
public bool BeginTransaction(string strServerName) {
try
{
bool bRet = OpenConnection(strServerName);
if (bRet)
{
m_objTransaction = m_conn.BeginTransaction();
m_dtAdapter.SelectCommand.Connection = m_conn;
return true;
}
}
catch (Exception ex)
{
return false;
}
return false;
}
public bool OpenConnection(string strServerName) {
try
{
m_connStr = string.Empty;
m_connStr = string.Format("Data Source=;Initial Catalog=;User Id=sa;Password=;"); //write your credentials here with DB name and server
m_conn = new SqlConnection(m_connStr);
m_conn.Open();
m_dtAdapter = new SqlDataAdapter();
if (m_conn != null)
{
m_dtAdapter.SelectCommand = new SqlCommand();
}
}
catch (SqlException ex)
{
return false;
}
catch (Exception ex)
{
return false;
}
return true;
}

Related

Connection string for local database not working

I have a database on my local machine on SQL Server Management studio.
The database connection information is as follows.
In my c# application, I have a connection string to connect to this database. I get an error though saying my connection string is incorrect. I have tried a number of different ones.
This is my function to connect to a database.
public virtual void openConnection()
{
con = new SqlConnection();
con.ConnectionString = "Server=DESKTOP-8UDMQUI\\WILLIAMSQL;Initial Catalog=team3db;TrustServerCertificate=true;";
try
{
con.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I have two \ in the server name because when I only have one, it has a red squiggle line under it throwing me an error on visual studio.
What should my connection string be? Note there is no password on this database.
Replace TrustServerCertificate = true; with Integrated Security = true

How can I fix the "File Activation Error" error message in SQL, from a program written in C#?

I write a C# program which uses a database, Matches.mdf.
I want to test the database file existence, using File.Exists routine (codes will come at the end of the question). If the file doesn't exist, the program creates a new database with the above name. To test the database existence routine, I renamed the database file, but when I wanted to create the database, I got the following error message: Database "Matches" already exists, please specify a different name.
At a second test, I used a database dropping routine before calling the creating routine. Big mistake. Every time I try to create the Matches.mdf database, I get the following error message:
I am sure that the cause of this error message is me, tinkering around, because the same database creation and deletion routines worked fine before.
I know I can solve the problem by changing the path of the database file, but I want to know what exactly I broke up here so I know for next time.
What I am asking is: what can I do to solve the above error?
Later edit: I tried to manually recreate the Matches.mdf using the query tool from SQL Server Object Explorer from VS 2019. Worked perfectly, but I don't think it's a good solution long term.
Necessary codes:
Variable declarations:
static readonly string DatabaseFolder = Path.GetDirectoryName(Application.ExecutablePath) + "\\db";
readonly string DatabaseFile = DatabaseFolder + "\\Matches.mdf";
readonly string DatabaseLog = DatabaseFolder + "\\MatchesLog.ldf";
The function that checks the database file existence:
public bool DatabaseExists()
{
return File.Exists(DatabaseFile);
}
The database creation routine:
private bool CreateDatabaseFile()
{
SqlConnection MyConn = new SqlConnection(CreateDatabaseConnectionString);
string Str = "Create Database Matches on Primary (Name=Matches, Filename='#DatabaseFile') log on (Name=MatchesLog, Filename='#DatabaseLog')";
SqlCommand DatabaseCreationCommand = new SqlCommand(Str, MyConn);
DatabaseCreationCommand.Parameters.Add("#DatabaseFile", SqlDbType.Text).Value = DatabaseFile;
DatabaseCreationCommand.Parameters.Add("#DatabaseLog", SqlDbType.Text).Value = DatabaseLog;
try
{
MyConn.Open();
DatabaseCreationCommand.ExecuteNonQuery();
}
catch (SqlException S)
{
MessageBox.Show(S.Message);
return false;
}
catch (IOException I)
{
MessageBox.Show(I.Message);
return false;
}
catch (InvalidOperationException I)
{
MessageBox.Show(I.Message);
return false;
}
catch (InvalidCastException I)
{
MessageBox.Show(I.Message);
return false;
}
finally
{
MyConn.Close();
}
return true;
}
The database deleting routine:
public void DeleteDatabase()
{
string Str;
SqlConnection MyConn = new SqlConnection(CreateDatabaseConnectionString);
Str = "Alter database Matches set single_user with rollback immediate\r\ndrop database Matches";
SqlCommand command = new SqlCommand(Str, MyConn);
try
{
MyConn.Open();
command.ExecuteNonQuery();
}
catch (SqlException S)
{
MessageBox.Show(S.Message);
}
catch (IOException I)
{
MessageBox.Show(I.Message);
}
catch (InvalidOperationException I)
{
MessageBox.Show(I.Message);
}
catch (InvalidCastException I)
{
MessageBox.Show(I.Message);
}
finally
{
MyConn.Close();
}
}
As it is said here and confirmed by Jeroen Mostert, Create database does not accept queries. The database was created before, using some string concatenation. Afterwards the query string was parametrized, without realizing that this command doesn't take parameters. This is why changing the creating database query to
Create Database Matches
works perfectly.
Well, live and learn!

Connect and insert data from my computer to server's MySQL DB table with the help of C#.NET

I want to connect with a server's MySql DB(cpanel) . Though there are no errors every time I'm getting a message for Messegebox : unable to connect to any of the specified any of the MySql hosts.
using MySql.Data.MySqlClient;
connString = "SERVER = ********;PORT=3306;DATABASE=********;UID=**********;PASSWORD=*********";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Server is online");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{ MessageBox.Show(ex.Message);}
If you try to connect to your MySQL server externally, external connections need to be enabled.
Be aware that it is a security hole if you provide your app to others which contain the DB information. To go around that, you need to create a Web-API.
The first step to connect to your app to a remote server MySql Server is verify if it allows external connections, for default the root user is locked, to allow local you can try to connect with the root user typing the following command in MySql:
GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
'root': You can change it with your user.
'%': allows all connections, you can limit it typing an IP.
Second step is verify your MySql .net connector
Cheers!
I would look into using ConnectionStringBuilder. Also note the use of 'using'. This will ensure resources are disposed once finished with.
private MySqlConnectionStringBuilder sConnString = new MySqlConnectionStringBuilder
{
Server = "",
UserID = "",
Password = "",
Database = ""
};
private void Test(){
// open connection to db
using (MySqlConnection conn = new MySqlConnection(sConnString.ToString()))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
try
{
conn.Open();
cmd.CommandText = "SELECT * FROM foo WHERE OrderID = #OrderID";
// Add any params
cmd.Parameters.AddWithValue("#OrderID", "1111");
cmd.Prepare();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
}

How to test connection to a data source in SSAS using C#

I have a database in Analysis Services on a remote server. This contains a data source for another database located on another remote server.
I am trying to write a connectivity test using C# which will check the database connection between the two databases.
I have been unable to do this using ADOMD.NET. I'm currently looking at using SMO to do this but I haven't had any luck so far.
I would greatly appreciate any advice or suggestions.
Update:
After further research, I have come up with the below test (Please note that I intend to add more try..catch blocks and Assertions later).
Also, this uses C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.AnalysisServices.DLL to access the Server, Database and
DataSource classes.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
try
{
connection.Open();
}
catch (OleDbException e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
I believe that this test is sufficient for my testing (Once I've added some more try..catch blocks and Assertions). If the test passes, it means there are no connectivity issues between my machine and both servers, which implies that there shouldn't be any connectivity issues between the servers.
However, I have been unable to work out how to test the connection between the two servers directly and I am interested if anyone knows a way of doing this.
The best solution I have come across to doing this connectivity test is below:
Please note that this requires the Microsoft.AnalysisServices.DLL to be added as a reference.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
try
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
connection.Open();
}
catch (Exception e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
}

problem with oracle connection in c#

I have a Windows XP machine used to create .Net applications with VS 2008.
I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.
I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.
I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.
What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.
I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.
Any help or suggestions are greatly appreciated. Thank you in advance.
//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";
public Oracle()
{
InitializeComponent();
}
//Methods
private void TestMyOracleConnection()
{
OracleConnection Conn = new OracleConnection(CONNSTR);
try
{
Conn.Open();
MessageBox.Show("Oracle Connection Established", "Success");
}
catch (OracleException ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
finally
{
Conn.Close();
MessageBox.Show("Oracle Connection Closed", "Success");
}
}
private void buttonTestConnection_Click(object sender, EventArgs e)
{
TestMyOracleConnection();
}
You might want to try something like:
connection string:
Data Source=DBNAME;User ID=zahid;Password= abc123;Persist Security Info=True;Unicode=True;
Now look in the tnsname.ora file on your PC. It will be somewhere under your local Oracle Client installation. You're looking for something like:
DBNAME =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1510))
(ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1514))
)
(CONNECT_DATA =
(SERVICE_NAME = DBNAME)
)
)
You're looking to replace DBNAME and OracleServerName with your own. Don't forget, DBNAME is the name of the main database, not one of the schemas (the entity with all the tables and procedures, etc) under it.
Assuming you are using ODP.Net, you can try a connection string such as the following (taken from a web.config):
<add name="OdpConnection" connectionString="Data Source=xe;User Id=some_user;Password=some_password; Promotable Transaction=local"
providerName="Oracle.DataAccess.Client" />
You can read this connection string from the web.config in your code using something like this:
string connectionString = ConfigurationManager.ConnectionStrings["OdpConnection"].ConnectionString;
It's a good practice to avoid putting connection strings directly in code, since to change them requires a re-compile. By putting them in a config file, such as web.config or app.config, you can change them without having to re-compile your library or exe.
try
{
Conn.Open();
MessageBox.Show("Oracle Connection Established", "Success");
}
catch (OracleException ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
finally
{
Conn.Close();
MessageBox.Show("Oracle Connection Closed", "Success");
}
You have pottential problem here: if conn.Open() fails (so connection is not opened) in finally you call conn.close(), but connection isn't opened - so it also fails, but it is now outside try catch. You need check for
if (Conn!=null && Conn.IsOpen())
Conn.Close();
Connection string for oracle:
Data Source=TORCL;User Id=myUsername;Password=myPassword;
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
More here

Categories

Resources