BizSnips

Snippets of knowledge to make life easier for a busy consultant

Connecting to a DB

Directly connecting to a database is generally not recommended when integrating with other systems. However, if you absolutely must connect straight to a database and run queries against it, here’s how you can do it.

Have the DB connection link

ConnectionsString = "Server=00.00.0.00,0000; Initial Catalog=DBNAME; User=username; Password=Password";

Initiate the connection to the database:

var connection = new System.Data.SqlClient.SqlConnection(); 
connection.ConnectionString = DBConnectionString;
var cmd = new System.Data.SqlClient.SqlCommand(); 
connection.Open();

Define the call and execute it:

var cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = "SELECT * FROM EXAMPLE_TABLE";
cmd.Connection = connection;  

var da = new System.Data.SqlClient.SqlDataAdapter();
da.SelectCommand = cmd; 
var dt= new System.Data.DataTable();
da.Fill(dt);

Close the connection:

connection.Close(); 
da.Dispose(); 

Read the results:

dt.Rows.Count - number of results
dt.Rows[i] - gets the row i of the defined data table 
row.ItemArray.Length - length of retrieved row
row.Table.Columns[i].ColumnName - name of the column
row[i] - the value of the cell. You can also call the value by the name of the field (dt.Rows[0]["FieldName"]);

Leave a Reply

Your email address will not be published. Required fields are marked *