Access a SQL database

Access a SQL database by using the System.Data.SqlClient library.

// This example needs the
// System.Data.SqlClient library

#region Building the connection string

string Server = "localhost";
string Username = "my_username";
string Password = "my_password";
string Database = "my_database";

string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;


#region Try to establish a connection to the database

SqlConnection SQLConnection = new SqlConnection();

SQLConnection.ConnectionString = ConnectionString;

// You can get the server version
// SQLConnection.ServerVersion
catch (Exception Ex)
// Try to close the connection
if (SQLConnection != null)

// Create a (useful) error message
string ErrorMessage = "A error occurred while trying to connect to the server.";
ErrorMessage += Environment.NewLine;
ErrorMessage += Environment.NewLine;
ErrorMessage += Ex.Message;

// Show error message (this = the parent Form object)
MessageBox.Show(this, ErrorMessage, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);

// Stop here


#region Execute a SQL query

string SQLStatement = "SELECT * FROM ExampleTable";

// Create a SqlDataAdapter to get the results as DataTable
SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(SQLStatement, SQLConnection);

// Create a new DataTable
DataTable dtResult = new DataTable();

// Fill the DataTable with the result of the SQL statement

// Loop through all entries
foreach (DataRow drRow in dtResult.Rows)
// Show a message box with the content of
// the "Name" column

// We don't need the data adapter any more


#region Close the database link




No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: