-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathDatabaseConnection.cs
More file actions
292 lines (246 loc) · 9.65 KB
/
DatabaseConnection.cs
File metadata and controls
292 lines (246 loc) · 9.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using System;
using System.Data.SqlClient; // for sql connection
using System.Data;
// To connect with external data source like database, xml file
// System.SQLClient package should be imported
// to connect with database SQLConnection class is used and
// to execute the query SQLCommand class is used
/*
* Steps to connect with database:
1. Import SQLClient class
2. Create connection string that contains all the necessary parameter to connect with database like server, dbname and security
3. Create object of SQLConnection class to connect with server
4. Write necessary query and handle SQLException
5. Execute the query using SQLCommand class
*/
/*
SqlClient => sql query and .net application
SqlConnection => to create connection between server and sql
SqlCommand => to know if the sql are correct
SQLReader => to fetch data
*/
namespace DatabaseConnection
{
class DatabaseConnection
{
private SqlConnection OpenConnection()
{
String server_name = "KSUYASH";
String dbname = "db_net";
String connectionString = $"Data Source={server_name};Initial Catalog={dbname};Integrated Security=true";
// integrated security = true means windows authentication
// if we want to use sql server authentication then we have to provide username and password
// in exam, data source can be SERVER
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
return conn;
}
/*
* Create table
*/
public void CreateTable()
{
try
{
string tableQuery = "CREATE TABLE tbl_emp IF_NOT_EXISTS(" +
"id INT PRIMARY KEY IDENTITY(1,1)," +
"name VARCHAR(255)," +
"age INT," +
"gender VARCHAR(50)," +
"department VARCHAR(50)," +
"salary FLOAT" +
")";
SqlConnection conn = OpenConnection();
/* Execute the query */
SqlCommand sc = new SqlCommand(tableQuery, conn); // first parameter => query, second parameter => connection
sc.ExecuteNonQuery(); // to execute the query
// use it for insert, update and delete
// not for display
Console.WriteLine("Table created successfully");
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
/*
* Insert static data
*/
public void InsertData()
{
try
{
/*Inserting into table */
string insertQuery = "INSERT INTO tbl_emp" +
"(name, age, gender, department, salary)" +
"VALUES('Suyash', 22, 'Male', 'IT', 50000)";
SqlConnection conn = OpenConnection();
SqlCommand sc = new SqlCommand(insertQuery, conn);
int response = sc.ExecuteNonQuery();
if (response > 0)
{
Console.WriteLine(response + " Data inserted successfully.");
}
else
{
Console.WriteLine(response + " Data insertion failed.");
}
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
/*
* Insert data from input of user
*/
public void InsertUserInput()
{
try
{
SqlConnection conn = OpenConnection();
Console.Write("Enter name: ");
string name = Console.ReadLine();
Console.Write("Enter age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter gender: ");
string gender = Console.ReadLine();
Console.Write("Enter department: ");
string department = Console.ReadLine();
Console.Write("Enter salary: ");
float salary = float.Parse(Console.ReadLine());
string insertQuery = "INSERT INTO tbl_emp" +
"(name, age, gender, department, salary)" +
"VALUES (@name, @age, @gender, @department, @salary)";
SqlCommand sc = new SqlCommand(insertQuery, conn);
sc.Parameters.AddWithValue("@name", name);
sc.Parameters.AddWithValue("@age", age);
sc.Parameters.AddWithValue("@gender", gender);
sc.Parameters.AddWithValue("@department", department);
sc.Parameters.AddWithValue("@salary", salary);
int response = sc.ExecuteNonQuery();
if (response > 0)
{
Console.WriteLine(response + " Data inserted successfully.");
}
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
/*
* Get all data from database
*/
public void GetAllData()
{
try
{
SqlConnection conn = OpenConnection();
string fetchQuery = "SELECT * FROM tbl_emp";
// to fetch the data, ExecuteReader is used.
SqlCommand sc = new SqlCommand(fetchQuery, conn);
SqlDataReader response = sc.ExecuteReader();
Console.WriteLine();
Console.WriteLine("---------------------------------------");
Console.WriteLine("Data from database:");
Console.WriteLine("---------------------------------------");
Console.WriteLine();
while (response.Read())
{
Console.WriteLine($"Id: {response["id"]}");
Console.WriteLine($"Name: {response["name"]}");
Console.WriteLine($"Age: {response["age"]}");
Console.WriteLine($"Gender: {response["gender"]}");
Console.WriteLine($"Department: {response["department"]}");
Console.WriteLine($"Salary: {response["salary"]}");
Console.WriteLine("--------------------------------------\n");
}
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
/*
* Get data of individual user by ID
*/
public void GetDataById()
{
try
{
SqlConnection conn = OpenConnection();
string fetchQuery = "SELECT * FROM tbl_emp WHERE id=@id";
SqlCommand sc = new SqlCommand(fetchQuery, conn);
Console.Write("Enter id to get: ");
int id = Convert.ToInt32(Console.ReadLine());
sc.Parameters.AddWithValue("@id", id);
SqlDataReader response = sc.ExecuteReader();
while (response.Read())
{
Console.WriteLine($"Id: {response["id"]}");
Console.WriteLine($"Name: {response["name"]}");
Console.WriteLine($"Age: {response["age"]}");
Console.WriteLine($"Gender: {response["gender"]}");
Console.WriteLine($"Department: {response["department"]}");
Console.WriteLine($"Salary: {response["salary"]}");
}
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
/*
* Update the data of user by ID
*/
public void UpdateData()
{
try
{
SqlConnection conn = OpenConnection();
string updateQuery = "UPDATE tbl_emp SET " +
"name=@name, salary=@salary " +
"WHERE id=@id";
Console.Write("Enter the id of user you want to update: ");
int id = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter new name: ");
string name = Console.ReadLine();
Console.Write("Enter new salary: ");
float salary = float.Parse(Console.ReadLine());
SqlCommand sc = new SqlCommand(updateQuery, conn);
sc.Parameters.AddWithValue("@id", id);
sc.Parameters.AddWithValue("@name", name);
sc.Parameters.AddWithValue("@salary", salary);
int response = sc.ExecuteNonQuery();
if (response > 0)
{
Console.WriteLine("Data updated.");
}
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
/*
* Delete the data of user by ID
*/
public void DeleteData()
{
try
{
SqlConnection conn = OpenConnection();
string deleteQuery = "DELETE FROM tbl_emp WHERE id=@id";
Console.WriteLine("Enter the id to delete: ");
int id = Convert.ToInt32(Console.ReadLine());
SqlCommand sc = new SqlCommand(deleteQuery, conn);
sc.Parameters.AddWithValue("@id", id);
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
}
}