How to connect to SQL Server from ASP?

How to connect to SQL Server (MSSQL) from ASP.NET (C#)?
How to connect to SQL Server from ASP.NET (C#)?
How to connect to SQL Server from ASP.NET?

// Main Code

1 string connectionString = "Data Source=DatabaseSERVER\SQLEXPRESS;Initial
Catalog=DatabaseName;Persist Security
Info=True;User ID=yourUserName;Password=yourPassword
"

2
3 db myDatabaseObject = new db(connectionString);
4
5 DataSet myDataSet = new DataSet();
6
7 myDatabaseObject.GetDbData("SELECT * FROM TableName", myDataSet);




// Create a class named db including code below
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Web;
5 using System.Web.Security;
6 using System.Web.UI;
7 using System.Web.UI.HtmlControls;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.WebControls.WebParts;
10 using System.Data.SqlClient;
11 using System.Collections;
12
13 /// <summary>
14 /// Database class includes database operation methods.
15 /// </summary>
16 public class db
17 {
18 SqlConnection connection = null;
19 string query = "";
20 bool dbResult = false;
21 DataSet dataSet = null;
22 string[] tables = { "Table1", "Table2", "Table3", "Table4" };
23 enum dbTables: int
24 {
25 Table1,
26 Table2,
27 Table3,
28 Table4
29 }
30
31
32 public db(string connectionString)
33 {
34 connection = new SqlConnection(connectionString);
35 connection.Open();
36 }
37
38 public SqlConnection Connection
39 {
40 get
41 {
42 return connection;
43 }
44 set
45 {
46 connection = value;
47 }
48 }
49
50 public void CloseDbConnection()
51 {
52 connection.Close();
53 }
54
55 public bool GetDbData(string query, ref DataSet ds)
56 {
57 try
58 {
59 SqlCommand cmd = new SqlCommand();
60 cmd.CommandTimeout = 0;
61 cmd.Connection = connection;
62 cmd.CommandText = query;
63 cmd.CommandType = CommandType.Text;
64 using (SqlDataAdapter da = new SqlDataAdapter(cmd))
65 {
66 ds = new DataSet();
67 da.Fill(ds);
68 cmd.Parameters.Clear();
69 }
70 return true;
71 }
72 catch
73 {
74 return false;
75 }
76 }
77
78 public bool WriteDbData(string query)
79 {
80 try
81 {
82 SqlCommand addCatCommand = new SqlCommand();
83 addCatCommand.Connection = connection;
84 addCatCommand.CommandText = query;
85 addCatCommand.ExecuteNonQuery();
86 return true;
87 }
88 catch
89 {
90 return false;
91 }
92 }
93 }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.