Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.ComponentModel;
- using System.Data;
- using System.Data.SqlClient;
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- // This example needs the
- // System.Data.SqlClient library
- #region Building the connection string
- string Server = "localhost";
- string Username = "sa";
- string Password = "fA4%1%bgsa5A";
- string Database = "msdb";
- string ConnectionString = "Data Source=" + Server + ";";
- ConnectionString += "User ID=" + Username + ";";
- ConnectionString += "Password=" + Password + ";";
- ConnectionString += "Initial Catalog=" + Database;
- #endregion
- #region Try to establish a connection to the database
- SqlConnection SQLConnection = new SqlConnection();
- try
- {
- SQLConnection.ConnectionString = ConnectionString;
- SQLConnection.Open();
- // You can get the server version
- // SQLConnection.ServerVersion
- }
- catch (Exception Ex)
- {
- // Try to close the connection
- if (SQLConnection != null)
- SQLConnection.Dispose();
- // 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
- return;
- }
- #endregion
- #region Execute a SQL query
- string SQLStatement = "SELECT * FROM [msdb].[dbo].[backupset]";
- // 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
- SQLDataAdapter.Fill(dtResult);
- // Loop through all entries
- foreach (DataRow drRow in dtResult.Rows)
- {
- // Show a message box with the content of
- // the "Name" column
- Console.WriteLine(drRow["Name"].ToString());
- }
- // We don't need the data adapter any more
- SQLDataAdapter.Dispose();
- #endregion
- #region Close the database link
- SQLConnection.Close();
- SQLConnection.Dispose();
- #endregion
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement