This tutorial is a step by step guide for accessing the database in MSSQL 2008 using C#.
Create a database named – student. Tables 1. Student info 2. Login_credentials.
Download this file to get database script. Run it in your sql server.
Prob statement - If database connection is successful, then display the message showing information about which database it is connected to, data source & version number of database engine
C# code –
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class _Default : System.Web.UI.Page
{
public SqlConnection connection;
public string connectionString = "Data Source=.\\SQLEXPRESS; Initial Catalog=Student; Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
try
{
connection = new SqlConnection(connectionString);
if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
lblMessage.Text = "Connection to '" + connection.Database + "' database on database engine"+connection.DataSource+" having version "+connection.ServerVersion+ " is successful";
}
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
}
finally
{
connection.Close();
}
}
}
Try running the code in c#. Here is the complete source code.
The code is pretty self-explanatory. Just go through it and let us know if you have any doubt.
No comments:
Post a Comment