I would like to share how to create a function to connect ASP.Net with
SQL Server 2008. In this post , i will guide you to create a function
in asp.net to connect to SQL Server 2008 and how to calling the function
on event load page.
function ConnectionToDB in Class connection :
public SqlConnection ConnectToDB() {
SqlConnection sqlcon = new SqlConnection();
// SqlConnection : Represents an open connection to a SQL Server database.
sqlcon.ConnectionString="Server= UBEE_THAROTH ;Database=Drink;uid=sa;pwd=123;";
try{
//open connection to SQL Server
sqlcon.Open();
return cn;
}catch (Exception ex){
// return null if can not connect to database in SQL Sever 2008
return null;
}
}
Note:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection();
//Calling function connectToDB sqlcon=connectToDB();
}
Done.....Hope this post useful for you.:) :)
Import two namespaces
//import these two namespaces :System.Data and System.Data.SqlClient to use .NET Framework Data //Provider for SQL Server
using System.Data;
using System.Data.SqlClient;function ConnectionToDB in Class connection :
public SqlConnection ConnectToDB() {
SqlConnection sqlcon = new SqlConnection();
// SqlConnection : Represents an open connection to a SQL Server database.
sqlcon.ConnectionString="Server= UBEE_THAROTH ;Database=Drink;uid=sa;pwd=123;";
try{
//open connection to SQL Server
sqlcon.Open();
return cn;
}catch (Exception ex){
// return null if can not connect to database in SQL Sever 2008
return null;
}
}
Note:
- UBEE_THAROTH : is server name.
- Drink : is database name.
- sa : is username to login in to database.
- 123 : is password to login in to database.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection();
//Calling function connectToDB sqlcon=connectToDB();
}
Done.....Hope this post useful for you.:) :)
Create function in asp.net to connect database in SQL Server 2008
Reviewed by BeiLover
on
12:52 PM
Rating:
No comments: