I have recently, with the help of Fishcake and Sevenhalo, figured out how to connect to a SQL Server and retrieve some data.
In order to expand my knowledge, my goal is to write a class that will encapsulate this code. I understand that writing a class for my tiny website may be a bit excessive, but its more for the knowledge of "how-to" than practicality.
The class that I have written does somewhat work:
The class is used like this:Code:using System; using System.Data; using System.Data.SqlClient; using System.Data.Sql; public class Database { private String DatabaseConnectionString = "Data source=*;" + "Database=*;" + "uid=*;" + "pwd=*"; private SqlConnection objConnection; private SqlCommand objCommand; public SqlDataReader objReader; public String dbError; public String GetConnectionString() { return DatabaseConnectionString; } private SqlConnection CreateConnection() { SqlConnection objConnection = new SqlConnection(DatabaseConnectionString); return objConnection; } private SqlCommand CreateCommand(String p_Command, SqlConnection p_Connection) { SqlCommand objCommand = new SqlCommand(p_Command, p_Connection); return objCommand; } //Article Related public void GetArticleByID(String p_CategoryID, String p_ArticleID) { objConnection = CreateConnection(); objCommand = CreateCommand("SELECT * FROM tblArticle " + "WHERE tblArticle.charArticleID=@Article " + "AND tblArticle.charCategoryID=@Category", objConnection); SqlDataReader objReader; try { objConnection.Open(); objCommand.Parameters.AddWithValue("@Article",p_ArticleID); objCommand.Parameters.AddWithValue("@Category",p_CategoryID); objReader = objCommand.ExecuteReader(); } catch(System.Exception ex) { dbError = ex.Message; objReader= null; } } //End Articles }
Question 1: Is my method even correct? Am I taking the right approach to this?Code:<script runat="server" language="c#"> protected void Page_Load(Object sender, EventArgs e) { String strCategoryID = Request.QueryString["ci"]; String strArticleID = Request.QueryString["ai"]; Database objDatabase = new Database(); objDatabase.GetArticleByID(strCategoryID,strArticleID); if(objDatabase.objReader != null) { while(objDatabase.objReader.Read()); { label1.Text += objDatabase.objReader["charTitle"].ToString(); } } else label1.Text = objDatabase.dbError; } </script>
I'm trying to create shortcuts by making functions that create the connectionstring and command for me without me having to type it out each time. The idea behind the class is that, it will do all the work for me and store a SqlDataReader object in itself, that I will then manipulate in my Page_Load event.
Any input in regards to this question is greatly appreciated. Thanks!





Reply With Quote