database INNER JOIN - c#

These are the two set up tables
LOGIN TABLE
USER'S NAME
I want to create something like the User will key in their USER_ID and USER_PWD in a textbox. IF the user successfully login, it will say " HI + PATNAME ".
I have created this code so far but it isnt working.
string sqlStr = "Select patpro.'PATNAME' FROM patpro,useform where USER_ID=#name and USER_PWD=#password and useform.'USER_ID' = patpro.'USERID'";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Password);
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.HasRows)
{
login.Read();
string name = (login["USER_ID"].ToString());
txtAssignID1.Text = "Login verified. Hi, " + name + "\n";
}

From what I see, you're trying to use login["USER_ID"].ToString() which USER_ID is a nonexistent column definition inside current SELECT statement. Hence, you should add column names which defined in SELECT results like login["PATNAME"] and use proper INNER JOIN statement instead:
string sqlStr = #"SELECT patpro.PATNAME FROM patpro INNER JOIN useform
ON useform.USER_ID = patpro.USERID
WHERE useform.USER_ID = #name AND useform.USER_PWD = #password";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Password);
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.HasRows)
{
// read value inside the loop, because MySqlDataReader is forward-only
while (login.Read())
{
string name = login["PATNAME"].ToString();
txtAssignID1.Text = "Login verified. Hi, " + name + "\n";
}
}
Additional note: Better to use using statement for MySqlConnection, MySqlCommand and MySqlDataReader to ensure immediate disposal of MySQL connection objects after fetching query results.

Related

How to connect this project with sql

executenonquery() error c#
this is how my code looks like
con.Open();
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String id = textBox3.Text.ToString();
int iid = Int32.Parse(id);
String semester = textBox4.Text.ToString();
int i_sem = Int32.Parse(semester);
String field = comboBox1.SelectedItem.ToString();
String qry = "insert into Table values('" + name + "','" + address + "'," + iid + "," + i_sem + ",'" + field + "',)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
executenonquery() always makes me problem !
int i = cmd.ExecuteNonQuery();
You need to fix a couple of things:
Remove the last , in your query.
I don't know if you have a table named Table in your database but you should check if the name is correct.
When you don't know how to correct your code it's better use the try-catch statement to understand where the real problem is in your code. Here is an example about how to handle SQL exception in C# code.
You are getting SqlException because your query syntax is wrong but there is another way to add SQL parameters into your query without need to use a string variable. You could use the SqlParameterCollection.AddWithValue(String, Object) method to achieve the same result and avoid SQL Injection:
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into YourTableName (name, address, id, semester, field) VALUES (#name, #address, #id, #semester, #field)";
command.Parameters.AddWithValue("#name", name);
command.Parameters.AddWithValue("#address", address);
command.Parameters.AddWithValue("#id", iid);
command.Parameters.AddWithValue("#semester", i_sem);
command.Parameters.AddWithValue("#field", field);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close(); //close your connection if you do not need to keep it open
}
More info:
AddWithValue Method
SQL Injection
Other examples related to this topic

C# SQL wrong INNER JOIN data is being displayed don't know why

The problem I have is I've made a program where user may log in to check their account information (login with username and password from SQL database) however if I log in with details A then log out and Log in with details B. it will still display account information of User A but with User B log in details.
public string Username { get; set; }
//gets Username from Login form (another form)//
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Graded unit Dev\BlackMarch\BlackMarch\bin\Debug\DataBaseBM.mdf;Integrated Security=True;Connect Timeout=30");
/* (2) */
SqlCommand cmd = new SqlCommand(#"SELECT *
FROM UserData
INNER JOIN HotelData
ON (UserData.Username = HotelData.Username) ", con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtboxPass.Text = dr["password"].ToString();
txtboxFN.Text = dr["FirstName"].ToString();
txtboxSurname.Text = dr["Surname"].ToString();
txtboxAge.Text = dr["Age"].ToString();
txtboxGender.Text = dr["Gender"].ToString();
txtboxMobile.Text = dr["Mobile"].ToString();
txtboxEmail.Text = dr["Email"].ToString();
txtboxRoomType.Text = dr["RoomType"].ToString();
txtboxNoRooms.Text = dr["NoOfRooms"].ToString();
txtboxPackage.Text = dr["PackageDeal"].ToString();
txtboxGym.Text = dr["Gym"].ToString();
txtboxBeach.Text = dr["Beach"].ToString();
txtboxPool.Text = dr["SwimmingPool"].ToString();
txtboxSports.Text = dr["SportsGround"].ToString();
txtDate.Text = dr["StartDateR"].ToString();
strNoNights = dr["NoOfNights"].ToString();
strNoDays = dr["NoOfDays"].ToString();
You aren't specifying the username in your query. A join will just return all the records for all users. If you want to get data for a specific user you need to use a parameterized query that passes in the name of the current user.
This query has no WHERE condition so your code gets all data produced by the JOIN but because your while loop replaces all the data from the previous loop with the current one you end up with your controls always showing the data of the last user read
To fix you need to add a WHERE condition to your sql text in such a way that only the data of the current logged in user will be retrieved. From your code I don't know how do you store the username of the logged in user so let's assume that is stored in a variable named UserName
string cmdText = #"SELECT *
FROM UserData
INNER JOIN HotelData
ON (UserData.Username = HotelData.Username)
WHERE UserData.UserName = #user";
using(SqlConnection con = new SqlConnection(#"....."))
using(SqlCommand cmd = new SqlCommand(cmdText, con);
{
con.Open();
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = UserName;
using(SqlDataReader dr = cmd.ExecuteReader())
{
// Now this will loop just one time, only for the logged in user
while (dr.Read())
{
....
}
}
}

C# checking if order number already exists

I've been looking into How to check user id already exists to see how to do this.
I am trying to get this working in my code, however it's not working. I don't get errors or something, but it just write data in database even if order number already exists.
The function:
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
cmd.Parameters.Add(param);
//sqlCommand.Connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
reader.Close();
}
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}
Sorry for this kinda well known and duplicated question, but for some reason I can't get it working.
You called the wrong command, change
SqlDataReader reader = sqlCommand.ExecuteReader();
to
SqlDataReader reader = cmd.ExecuteReader();
The problem is here:
SqlDataReader reader = sqlCommand.ExecuteReader();
You should execute the other command first
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
The latter command, when will be executed will tell you if there is any record in the testtabel table. If there is, then you should show the message:
Order already exist
Otherwise, you will execute your first command, that will insert the rows.
By the way, please try to avoid string concatenation, when you write sql queries. It is one of the most well known security holes. You code is open to SQL injections. You could use parameterized queries:
String query = "INSERT INTO testtabel (knaam, korder) VALUES (#knaam, #korder)";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
sqlCommand.Parameters.Add(new SqlParamete("#knaam",knaamTextBox.Text));
sqlCommand.Parameters.Add(new SqlParamete("#korder",kordernrTextBox.Text));
While your code is full of problems (magic pushbutton, SQL injections, absence of usings), there is main one. The approach you want to implement will fail on concurrent inserts, and must not be used.
Imagine, that two users run this code against the same database, using the same korder value:
1st executes SELECT - record with the given value doesn't exist;
2nd executes SELECT - record with the given value doesn't exist;
1st executes INSERT - record with the given value does exist;
2nd executes INSERT - ooops... we have a duplicate;
To avoid duplicates you must use unique indexes in database. Do not rely on your code.
You check HasRows for INSERT INTO testtabel bla...bla..bla.. not for `elect * from testtabel where korder'
Maybe you can use this (it comes from my head and not compiled, please adjust it with your own case)
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
//sqlCommand.Connection.Open();
SqlDataReader cmdReader = sqlCommand.ExecuteReader();
if (cmdReader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
cmdReader.Close();
}
SqlDataReader reader = sqlCommand.ExecuteReader();
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}

How to get/display the user-information after logging in. ASP.net C#

I am implementing an online voting system for my school-project.
After the voter's log-in, i want to display their name, and ID in the label control at the content body. I try to use SESSION to store the voter's username in the log-in page but I'm not sure of my syntax because nothings happen.
I want to know the other way of retrieving a data from database! Please teach me.
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Session["VotersID"] + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Please Help Me. Thanks! -
#Honey Maglangit , what you use is PARAMETER not SESSION.
Response.Redirect("VoterPage.aspx?VotersID="+VoterUsername.Text);
So, you should get your VotersID by this way:
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Request.QueryString["VotersID"].ToString() + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Try it again.
You can use LogonUserIdentity as follow
if (Request.LogonUserIdentity.IsAuthenticated)
lblName.Text = Request.LogonUserIdentity.Name;
just add this namespace:
using Microsoft.AspNet.Identity;
then you can get LoggedInUserId by:
User.Identity.GetUserId();
Or
HttpContext.Current.User.Identity.GetUserId();
So you don't need to use session to keep UserId.
Also you can create Custom Identity and instead of save Username in Name property, storing custom string Store User Data in ASP.NET Identity
get session data and send to one page(register.aspx) to another page(user_home.aspx)
Session["remail2"] = txtemailsignin.Text;
Server.Transfer("user_home.aspx", true);
display the user-information after logging
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["socailweb"].ConnectionString);
string sql = "select * from tblUsers where remail='" + Session["remail2"] + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
lblVotersID.Text = sqldr.GetValue(2).ToString();
lblVoterName.Text = sqldr.GetValue(3).ToString();
}
sqldr.Close();
con.Close();

syntax error in from clause C# and Access

I keep getting this run time error, syntax error in from clause. I tried already using my sql query in access and it seems ok.
Here's my code and I am using C# windows form with text box and button
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Misry27\Documents\Visual Studio 2010\Projects\Inventory\Inventory\bin\Debug\Inventory.mdb");
OleDbCommand cmd = new OleDbCommand("select * from Employee where username = '" + this.tbUsername.Text + "' and password = '" + this.tbPassword.Text + "';", conn);
OleDbDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username or Password is correct");
}
else
{
MessageBox.Show("Username or Password Incorrect");
}
conn.Close();
As explained in the comments above, PASSWORD is a reserved keyword and need to be enclosed in square brackets when used in query executed from net.
The usual advice follows. Use parameterized query to avoid parsing problem and sql injections, use the using statement around your disposable objects.
using(OleDbConnection conn = new OleDbConnection(a correct connection string here))
using(OleDbCommand cmd = new OleDbCommand(#"select * from Employee
where username = ? AND [Password] = ?", conn);
{
conn.Open();
cmd.Parameters.AddWithValue("#p1", this.tbUsername.Text);
cmd.Parameters.AddWithValue("#p2", this.tbPassword.Text);
using(OleDbDataReader dr = cmd.ExecuteReader())
{
.....
}
}

Categories

Resources