Storing table column value into variable (SQL Server) - c#

I have been stuck on this problem for some time: I am trying to save a value from a column in a table (database), under a certain condition.
In the code below I am trying to compare the input of a textbox (sUserName) with a value in a column (UserName) in the table (aspnet_Membership). If these values are equal, I want to fetch the specific Email value in a column and save it as a string variable.
If UserName (column) does not equal sUserName (textbox), then I would like to display an error message (else statement). The Email and UserName column are in the same table
string sUserName = txtBoxUsername.Text;
SqlConnection conn2 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\sunny\Visual Studio 2010\Projects\email\Prac 2\App_Data\aspnet_Membership.mdf;Integrated Security=True;User Instance=True");
SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = sUserName", conn2);

Just add checking if user exist on your table to your code something like:
string sUserName = txtBoxUsername.Text;
SqlConnection conn2 = new SqlConnection("Your SQL Connection");
SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = '"+ sUserName + "'", conn2);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string email = rdr["Email "].toString();
}
}
else
{
//Error! user not exist
}
Best Regards

Related

I'm validating a form in C# but I don't know what I am doing wrong. Please help me solve this

I'm creating a validation for form data coming from database and then comparing it with data entered in textboxes. It always executes else part whether I enter correct or incorrect data in textboxes, please help with this.
c.Uname = Text1.Value.ToString();
c.Cnic = Text2.Value.ToString();
c.pass = Text3.Value.ToString();
SqlConnection sqlConn = new SqlConnection(#"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("select Uname , Cnic, password from carregister", sqlConn);
sqlConn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
while (dr.Read())
{
name = dr["Uname"].ToString();
cnic = dr["Cnic"].ToString();
passs = dr["password"].ToString();
if (name.Equals(c.Uname) && cnic.Equals(c.Cnic) && passs.Equals(c.pass))
{
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else
{
Response.Redirect("wrongidpass.aspx");
}
}
You are reading ALL rows of your usertable and start comparing with the first received row. If this doesn't match, you are already redirecting ...
You could count only the matching rows from your database, and if that returns anything other than 1, there is an error with username or password (or your database).
c.Uname = Text1.Value.ToString();
c.Cnic = Text2.Value.ToString();
//you don't store plaintext passwords in your db, do you?
c.pass = hash_the_password(Text3.Value.ToString());
SqlConnection sqlConn = new SqlConnection(#"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("SELECT COUNT(*) FROM carregister WHERE uname = #uname and cnic = #cnic and password = #hashedpassword", sqlConn);
sqlComm.Parameters.Add("#uname", SqlDbType.NVarchar).Value = c.Uname;
sqlComm.Parameters.Add("#cnic", SqlDbType.NVarchar).Value = c.Cnic;
sqlComm.Parameters.Add("#hashedpassword", SqlDbType.NVarchar).Value = c.pass;
sqlConn.Open();
if (Convert.ToInt32(sqlComm.ExecuteScalar()) == 1) {
//you have exactly one row where uname, cnic and password match the entered values
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else
{
//no row matched
//(or more than one which is an error in the database, because uname should probably be unique)
Response.Redirect("wrongidpass.aspx");
}

How to convert Integer from database into string in textbox?

This is a little piece of code I wrote to autocomplete my textbox from the database as I type:
{
SqlConnection connString = new SqlConnection();
connString.ConnectionString = "Data Source=************************;Initial Catalog=STUPELG;Persist Security Info=True;User ID=****************;Password=**********";
SqlDataAdapter adapter = new SqlDataAdapter();
connString.Open();
SqlDataReader dataReader;
SqlCommand command = new SqlCommand("SELECT Name FROM dbo.Entity WHERE Name LIKE #name", connString);
command.Parameters.Add(new SqlParameter("#name", "%" + tbEntity.Text + "%"));
command.ExecuteNonQuery();
dataReader = command.ExecuteReader();
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
while (dataReader.Read())
{
col.Add(dataReader.GetString(0));
}
tbEntity.AutoCompleteCustomSource = col;
connString.Close();
}
However, I want to display two fields (EntityID, Name) out of the database into the textbox, but
I do not know how to display more than one field.
EntityID is an integer and I am not sure how to convert it to string in my code.
Any suggestions?
Usually a textbox is not used to display more than one data coming from the database. But also notice that autocomplete is a tool to help your end users to choose while typing.
If you want to add also the EntityID you need to add it after the name in the autocomplete source.
First you need to change the sql command to retrieve also the EntityID field and not just the Name field
string cmdText = "SELECT Name, EntityID FROM dbo.Entity WHERE Name LIKE #name";
SqlCommand command = new SqlCommand(cmdText, connString);
Then inside the loop that read the values you add both the Name and the EntityID as part of the string added to the autocomplete collection
while (dataReader.Read())
{
string data = $"{dataReader.GetString(0)} {dataReader.GetInt32(1)}"
col.Add(data);
}

How to Delete rows in database based on Username in ASP.Net?

I am trying to delete few rows by Username. But my sql query apparently not working right. instead of reading the column username, it looks for the name as a column...
Edit: What im trying to achieve is to remove rows with the username John Rose... but insead it says its looking for the column name John Rose
System.Data.SqlClient.SqlException: 'Invalid column name 'Jack Rose'.'
This code is in the checkout button. Im showing the whole code just incase the cause might be outide of the delete query code.
protected void Button1_Click(object sender, EventArgs e)
{
string Username = Session["Username"].ToString();
con.Open();
string query = "INSERT INTO GuestOrder (Order_Id, Username, Order_Date, GrandTotal) values (#Order_Id, #Username, #Order_Date, #GrandTotal)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Order_Id", Label_OrderId.Text);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Order_Date", Label_OrderDate.Text);
cmd.Parameters.AddWithValue("#GrandTotal", Label_Grand.Text);
cmd.ExecuteNonQuery();
con.Close();
string sql = "DELETE FROM Cart WHERE Username =" + Username+"";
con.Open();
SqlCommand cmd1 = new SqlCommand(sql, con);
cmd1.ExecuteNonQuery();
con.Close();
con.Dispose();
string strSQL = "SELECT * FROM GuestOrder";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet("orderdetails");
dt.Fill(ds, "order");
ds.WriteXml(Server.MapPath(#".\xml\orders.xml"));
Response.Redirect("SuccessfulOrder.aspx");
con.Close();
}
You should use this as below:
string sql = "DELETE FROM Cart WHERE Username = #Username";
You need to put username in single quotes as below
string sql = "DELETE FROM Cart WHERE Username = '" + Username+"'";
or You can use parameterized version of this query to avoid the sql injection as
below:
string sql = "DELETE FROM Cart WHERE Username = #Username";

C# and MySql changing column var

I'm making mysql register/login system in c#. I'm able to register and login with it.
I'm verify account with:
MySqlConnection conn = new MySqlConnection(db_creds);
try { conn.Open(); }
catch { throw new Exception("Can't access database"); }
MySqlDataAdapter adapter;
DataTable table = new DataTable();
string query = "SELECT `Nickname`, `Password` FROM `" + db_table + "` WHERE `Nickname` = '" + nickname + "' AND `Password` = '" + password + "'";
adapter = new MySqlDataAdapter(query, conn);
adapter.Fill(table);
conn.Close();
if(table.Rows.Count <= 0)
{
return false;
}
else { return true; }
After Nickname and Password I have varchar named active. My question is:
How can I change "active" (only for this user) to 1 when user succesfully logged in? and when logoff change it to 0?
To alter a single row in the table, you need to get it's ID(unique identifier for this table). Let the name for this unique column be str_Id, then retrieve this id for the particular user name and password. Then you can update the active state based on this unique identifier.
Another important advise for you is, don't use this type of plain-text queries, which will opens a wide door for SQL Injection. So i strongly recommend you to use parameterized queries as follows;
string query = "SELECT Nickname,str_Id FROM your_table_name" +
" WHERE Nickname =#nickname AND Password = #password";
MySqlConnection con = new MySqlConnection();
// Creating parameterized command
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#nickname", MySqlDbType.VarChar).Value = nickname;
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = password;
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();
// Collect the details to a DataTable
adapter.Fill(table);
if (table.Rows.Count>0) // Means there is some record found
{
// Get theUnique ID for the matching record
string uniqueId = table.Rows[0]["str_Id"].ToString();
// Update active state for that particular user
query = "Update your_table_name set active='0' Where str_Id=#str_Id";
cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#str_Id", MySqlDbType.VarChar).Value = uniqueId;
// Execute command here
}
else
{
// Print message thet no user found
}
When you verify if user exists and if password is correct and return message there you need to add update command for your database.
With that update command you need to update column ACTIVE to 1 but to that user, so you need to use this:
UPDATE table_name
SET column1=value1
WHERE some_column=some_value;
So in your case
UPDATE db_table SET active = 1 WHERE nickname = ' + nickname + '
So user now have status of ACTIVE.
Now you need to set it to inactive when he log off, so you do that when he press log off button or when he close the program, but with same principle
UPDATE db_table SET active = 0 WHERE nickname = ' + nickname + '

How to prevent adding same data to SQL from C# program

This is our code to prevent the same data from being added into SQL from our C# program but only the first same data will not be added in. The remaining ones adds the same data into SQL despite our prevention in our C# program. Can somebody help us troubleshoot?
in order not to duplicate data in database usually you set some constraints to your database. By having a unique field in database you can prevent multiple addition to your db.
Currently you are also fetching data from db to check if it exist already and that creates extra cost, just manipulate the design of db so that it won't accept the same column input twice
Count the value of data that is inserted
string constr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
SqlConnection con = new SqlConnection(constr);
string sql1 = "SELECT COUNT (client_id) FROM client WHERE client_id = '" + txtid.Text + "' ";
SqlCommand cmd = new SqlCommand(sql1, con);
con.Open();
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp >0)
{
//show error message
}
You could check for the record you want to add, and if it doesn't exists, then add it to the table:
SqlConnection _cnt = new SqlConnection();
_cnt.ConnectionString = "Your Connection String";
SqlCommand _cmd = new SqlCommand();
_cmd.Connection = _cnt;
_cmd.CommandType = System.Data.CommandType.Text;
_cmd.CommandText = "SELECT id FROM myTable where Category=#Name";
_cmd.Parameters.Add("#Name", string);
_cmd.Parameters["#Name"].Value = newCatTitle;
_cnt.Open();
var idTemp = _cmd.ExecuteScalar();
_cmd.Dispose();
_cnt.Close();
_cnt.Dispose();
if (idTemp == null)
{
//Insert into table
}
else
{
//Message it already exists
}

Categories