I am trying to see if there is a shorter way of writing the code to run the SQL query. I was using Entity Framework before but it seems to load way slower than using SQL commands. Any suggestion would be great. Thanks in advance!
Here is the code to my SQL commands:
string query = "Select Count(*) From Employee Where Email = #Email And Password = #Password";
string queryEmployeeId = "Select EmployeeId From Employee Where Email =#Email and Password = #Password";
string queryAdmin = "Select Admin From Employee Where Email =#Email and Password = #Password";
string queryFirstName = "Select FirstName From Employee Where Email =#Email and Password = #Password";
int result = 0;
int employeeId = 0;
int admin = 0;
string employeeFirstName;
using (SqlConnection connection = new SqlConnection(#"Data Source=198.71.227.2;Initial Catalog=TaskManager;Integrated Security=False;User ID=;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
connection.Open();
result = (int)command.ExecuteScalar();
}
using (SqlCommand command = new SqlCommand(queryEmployeeId, connection))
{
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
employeeId = (int)command.ExecuteScalar();
}
using (SqlCommand command = new SqlCommand(queryAdmin, connection))
{
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
admin = (int)command.ExecuteScalar();
}
using (SqlCommand command = new SqlCommand(queryFirstName, connection))
{
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
employeeFirstName = (string)command.ExecuteScalar();
}
}
if (result > 0)
{
Session["EmployeeId"] = employeeId;
Session["Admin"] = admin;
Session["EmployeeFirstName"] = employeeFirstName;
Response.Redirect("~/MyJobSheet.aspx");
}
Originally, this was my code for the Entity Framework:
string username = txtEmail.Text;
string password = txtPassword.Text;
using (TaskManagerEntities myEntities = new TaskManagerEntities())
{
var employee = (from a in myEntities.Employees
where a.Email == username && a.Password == password
select new { a.EmployeeId, a.Admin, a.Email, a.Password, a.FirstName }).SingleOrDefault();
if (employee != null)
{
Session["EmployeeId"] = employee.EmployeeId;
Session["Admin"] = employee.Admin;
Session["EmployeeFirstName"] = employee.FirstName;
Response.Redirect("~/MyJobSheet.aspx");
}
Write a single Stored procedure which returns a table with the following columns EmployeeID, Admin, EmployeeFirstname .Also the check whether the employee exists can be done in the Stored procedure itself (Better to user IF exists instead of count(*)).
By doing this there will be only one database call instead of 4.Also as Steve mentioned make sure that the Email column is indexed
ADO.NET will always be more efficient that any ORM, because its more "low level", what you can do is turn off some features that Entity Framework provide, when you are performing read only query's. For example you case AsNoTracking() for getting your entities, but is not necessary to keep your context tracking them.
var blogs2 = context.Blogs
.Where(b => b.Name.Contains(".NET"))
.AsNoTracking()
Or you can use Dapper, to make a Repository for Read-Only query's for each entity, it uses ADO.Net approach, but is more productive to work than pure ADO.Net
Related
I'm trying to get the UserName and put it in TempData but I get an error when the code reaches the ExecuteReader() method.
Here's my query code:
var InvoiceId = TempData["newinvoice"];
TempData["invoiceid"] = InvoiceId;
var UserID = TempData["UserID"];
string connection = "Data Source=.;Initial Catalog=project;Integrated Security=true;";
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = new SqlCommand("SELECT UserName FROM AspNetUsers WHERE Id = #id"))
{
sqlcomm.Parameters.Add("#id", SqlDbType.VarChar).Value = UserID;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sqlcomm.Connection = sqlconn;
sqlconn.Open();
sda.SelectCommand = sqlcomm;
SqlDataReader sdr = sqlcomm.ExecuteReader();
while (sdr.Read())
{
TempData["UserId"] = sdr["UserName"];
}
}
}
}
The User Id from TempData["UserID"] is an nvarchar(450) not an integer. I have no clue why that exception is happening - any help?
Note: here's an example from one of my user ids:
'aa776084-053e-452c-8b0d-b445cdbf457d'
It looks like your id is a uniqueidentifier and if so I would recommend changing your database and code to use GUIDs.
However to fix your problem, you should be able to pass in the UserId and call toString() (as the value is most likely an object) e.g:
sqlcomm.Parameters.Add("#id", SqlDbType.NVarChar, UserID.ToString());
If you're only going to return one results, maybe use ExecuteScalar()
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = new SqlCommand("SELECT TOP 1 UserName from AspNetUsers where Id=#id", sqlconn)
{
sqlcomm.Parameters.Add("#id", SqlDbType.NVarChar, UserID.ToString());
object result = sqlcomm.ExecuteScalar();
if (result != null)
{
TempData["UserId"] = result.ToString(); // It looks like you're mixing UserId & UserName .
}
}
}
How to add multiple column values from a SQL Server database and insert in session[]?
Just FirstName is working, when I add LastName, I get an error.
string constr = sql connection here.... ;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = #email"), cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = #email"))
{
cmd.Parameters.AddWithValue("#email", TextboxUsr.Text);
cmd.Connection = con;
cmd2.Parameters.AddWithValue("#email", TextboxUsr.Text);
cmd2.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.Read())
{
string fName = sdr["FirstName"].ToString();
//string lName = sdr["LastName"].ToString();
string userFullName = fName;
Session["New"] = userFullName;
}
}
//con.Close();
}
}
Step 01 : Read more about SQL and C# Basics
you need to read more in
SQL SELECT Statement
.net - What is the C# Using block and why should I use it? - Stack Overflow
c# - SqlConnection.Close() inside using statement - Stack Overflow
c# - var versus concrete type usage - Stack Overflow
$ - string interpolation - C# Reference | Microsoft Docs
Step 02 : Use Select in a correct way
change
SqlCommand
cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = #email"),
cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = #email"))
to
SqlCommand
cmd = new SqlCommand("SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = #email")
Step 03 : read the full code
var sql = #"SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = #email";
using (var con = new SqlConnection(constr))
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
cmd.Parameters.AddWithValue("#email", TextboxUsr.Text);
using (var sdr = cmd.ExecuteReader())
{
if (sdr.Read())
{
var fName = sdr["FirstName"].ToString();
var lName = sdr["LastName"].ToString();
var userFullName = fName + " " + lName;
Session["New"] = userFullName;
}
}
}
Not sure why the following code gives me an exception. I'm trying to check if a username exists in a MySQL database, if not then I want to create a user. If I run either query by itself then it works ok but not together.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
string sql1 = String.Format("SELECT Username FROM Users WHERE Username = \"{0}\"", username);
MySqlCommand cmd1 = new MySqlCommand(sql1, cnn);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
string sql = String.Format("INSERT INTO Users(Username, Password) VALUES(\"{0}\", \"{1}\")", username, password);
MySqlCommand cmd = new MySqlCommand(sql, cnn);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
First, MySQL uses single quotes. This means your query would be:
string.format("SELECT Username FROM Users WHERE Username = '{0}' LIMIT 1", Username);
However, this is very vulnerable with SQL injection. Here's a code to use MySQL Parameters to prevent it.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
cmd1.Parameters.AddWithValue("#username", username);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO Users(Username, Password) VALUES(#username, #password)", cnn);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
Could you try this?
I got it working by changing the first query from:
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
to
MySqlCommand cmd1 = new MySqlCommand("SELECT COUNT(UserID) FROM Users WHERE Username = #username", cnn);
int valid = int.Parse(cmd.ExecuteScalar().ToString());
Thanks for the help.
I am trying to get a simple SQLite database working. I'm using the official SQLite extension for C# and I'm using DataGrip from IntelliJ to verify the data is there, yet my C# program doesn't get any results.
This is the code that executes the query:
SQLiteConnection connection = new SQLiteConnection(DbDsn);
User user = new User();
using (connection)
{
connection.Open();
string sql = "SELECT * FROM user WHERE username = #username ;";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.Prepare();
command.Parameters.AddWithValue("#username", username);
SQLiteDataReader reader = command.ExecuteReader();
if (reader.Read())
{
user.Id = (int) reader["id"];
user.Username = reader["username"] as string;
user.Password = reader["password"] as string;
user.Name = reader["name"] as string;
user.LastName = reader["last_name"] as string;
user.Type = (UserTypes) reader["type"];
}
else
{
throw new ObjectNotFoundException();
}
connection.Close();
}
And this is the result of a simple Select * From user; query on the user table (done on DataGrip):
id username passw… name last_name type
1 managertest oAWpW… BENJAMIN ARIEL NAVA MARTINEZ 1
2 clerktest iRYMz… EMPLEADO PRUEBA 0
As you can see, the records are there (an I've verified that the query is being performed on the exact same file), however, the C# program seems to skip the if statement (because read returns false) as if there were no rows in the database, what is the problem here?
Call SQLiteCommand.Prepare AFTER you have completed constructing your command
//...
string sql = "SELECT * FROM user WHERE username = #username ;";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.Parameters.AddWithValue("#username", username);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
SQLiteDataReader reader = command.ExecuteReader();
//...
i have table where have 5 columns :
i wrote the code like this :
String SQLQuery = "SELECT count(*) FROM aspnet_Users where Username=#uname AND Password = #pwd";
using(SqlConnection sqlConnection = new SqlConnection(strConnection))
using(SqlCommand command = new SqlCommand(SQLQuery, sqlConnection))
{
sqlConnection.Open();
command.Parameters.AddWithValue("#uname", Username);
command.Parameters.AddWithValue("#pwd", Password);
int result = Convert.ToInt32(command.ExecuteScalar());
boolReturnValue = (result > 0);
}
here few more extra information i needed,if above Username and password is correct,
what i need is : userid, and role column data
Why you aren't doing that instead ?
string SQLQuery = "SELECT UserId FROM aspnet_Users where Username=#uname AND Password = #pwd";
[...]
object result = command.ExecuteScalar();
if (result == null)
{
boolReturnValue = false;
}
else
{
long userId = Convert.ToInt64(result);
boolReturnValue = true;
}
String SQLQuery = "SELECT Top 1 UserId, role FROM aspnet_Users where Username=#uname AND Password = #pwd";
using(SqlConnection sqlConnection = new SqlConnection(strConnection))
using(SqlCommand command = new SqlCommand(SQLQuery, sqlConnection))
{
sqlConnection.Open();
command.Parameters.AddWithValue("#uname", Username);
command.Parameters.AddWithValue("#pwd", Password);
SqlDataReader Reader = null;
if (sqlConnection.State == ConnectionState.Closed || sqlConnection.State == ConnectionState.Broken)
sqlConnection.Open();
Reader = command.ExecuteReader();
if (Reader.Read())
{
int UserId = Convert.ToInt32(Reader["UserId"]);
string Role = Convert.ToString(Reader["role"]);
}
}
Why don't you just get the UserId instead of the Count(*) so your query should look like this :
SELECT UserId FROM aspnet_Users where Username=#uname AND Password = #pwd
Username should be unique so you shouldn't retrieve more than one row...you can add a Top 1 in case you have multiple same username with same password.
Try this Code
SELECT count(*),userid,role FROM aspnet_Users where Username=#uname AND Password = #pwd Group by userid,role