1. Include following :
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
Note that the third line is not much documented, but since Database is an abstract class, its instance cannot be created.
Hence you need database specific database class, which for sql is SqlDatabse.
To use sqldatabase, you need the last line above.
2. The simplest code to access a table is :
string sql = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";
SqlDatabase abc = new SqlDatabase(sql);
GridView1.DataSource = abc.ExecuteReader(CommandType.Text, "SELECT * FROM TABLE1");
GridView1.DataBind();
3. The next case is about adding parameters. For this you may use DbCommand object and
Database.AddInParameter method.
Not that you need to include
using System.Data.Common;
to use DbCommand object.
string sql = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";
SqlDatabase abc = new SqlDatabase(sql);
DbCommand cc = abc.GetSqlStringCommand("SELECT * FROM TABLE1 WHERE ID > @ID");
abc.AddInParameter(cc, "ID", DbType.Int32, 2);
GridView1.DataSource = abc.ExecuteReader(cc);
GridView1.DataBind();
The includes for this code are :
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
Similarly you can use ExecuteNonQuery etc.
No comments:
Post a Comment