Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Data.OleDb;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CRUDDummyAccessConsole3a
- {
- class User
- {
- private OleDbConnection aConnection;
- private string table = "users";
- public int Id { get; set; }
- public string Username { get; set; }
- public string Password { get; set; }
- public string Email { get; set; }
- public void Find(int id)
- {
- // Hydration
- OleDbDataReader aReader = null;
- OleDbCommand aCommand = new OleDbCommand("SELECT * FROM users WHERE id = @par1", aConnection);
- aCommand.Parameters.AddWithValue("@par1", 1);
- try
- {
- aConnection.Open();
- aReader = aCommand.ExecuteReader();
- // Console.WriteLine("This is the returned data from users table");
- this.Id = aReader.GetInt32(0);
- this.Username = aReader.GetString(1);
- this.Password = aReader.GetString(2);
- this.Email = aReader.GetString(3);
- aReader.Close();
- aConnection.Close();
- }
- catch (OleDbException e)
- {
- Console.WriteLine("Error {0}", e.Errors[0].Message);
- }
- finally
- {
- aReader.Close();
- aConnection.Close();
- }
- }
- public int Save()
- {
- int numberOfRows = 0;
- OleDbCommand aCommand = null;
- try
- {
- aConnection.Open();
- // SQL Injection
- // OleDbCommand aCommand = new OleDbCommand("UPDATE users SET username = 'updatedUsername' WHERE ID = " + ID, aConnection);
- if (this.Id != 0)
- {
- aCommand = new OleDbCommand("UPDATE users SET username = 'updatedUsername' WHERE ID = @par1", aConnection);
- aCommand.Parameters.AddWithValue("@par1", Id);
- }
- else
- {
- aCommand = new OleDbCommand("INSERT INTO users (username, `password`, email) VALUES ('О''Харра','insertedPass', '[email protected]')", aConnection);
- }
- // 1. approach with AddWithValue
- // aCommand.Parameters.AddWithValue("@par1", ID);
- // or
- // 2.
- aCommand.Parameters.AddRange(new[] {
- new OleDbParameter("@par2", Username),
- new OleDbParameter("@par3", Password),
- new OleDbParameter("@par4", Email)
- });
- numberOfRows = aCommand.ExecuteNonQuery();
- Console.WriteLine("The number of rows during Update were {0}", numberOfRows);
- aConnection.Close();
- }
- catch (OleDbException e)
- {
- Console.WriteLine("Error {0}", e.Errors[0].Message);
- }
- finally
- {
- aConnection.Close();
- }
- return numberOfRows;
- }
- public bool HasIdentity()
- {
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement