I want to check if a username is already in the database. It comes along with my update statement. I have this code and I do not know where to put the select statement:
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "update UserData set Password=#Password where UserName='" + txtUser.Text + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar));
com.Parameters["#Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text);
com.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
con.Close();
}
I want something like
"Select Username from Userdata Where Username = txtUser.Text"
You don't need a SELECT here. ExecuteNonQuery() returns the number of rows affected, which means that when it returns 0, there was no user with the given name in the database. If all went well, it should return 1.
Your code is vulnerable to SQL injection and leaks resources. Here's a better version:
protected void btn_update_Click(object sender, EventArgs e)
{
using(var con = new SqlConnection(conn))
{
con.Open();
var commandTest = "update UserData set Password=#Password where UserName=#Username";
using(var com = new SqlCommand(commandTest, con))
{
com.Parameters.AddWithValue("#Username", txtUser.Text);
com.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
if(com.ExecuteNonQuery() == 1)
{
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
}
}
}
}
Related
I always get the "else", even though I add the correct username and password
Photo with the script
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CONSTRing);
con.Open();
string q = "select * from LOGG where username = '" + tbu.Text + "' and password = '" + tbp.Text + "'";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter Da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
Da.Fill(DT);
if (DT.Rows.Count == 1)
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
}
Photo with dbo.LOGG
I will try to be helpful with an answer since I can't yet comment ;_;
Below is some code I compiled as an improvement to the one you posted.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string q = "select 1 from LOGG where username = #username and password = #password";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#username", tbu.Text); //
cmd.Parameters.AddWithValue("#password", tbp.Text); // using parameters to avoid intentional or accidental SqlInjection by the user
using (SqlDataReader reader = cmd.ExecuteReader())
{
try
{
con.Open();
if (reader.Read())
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
cmd.Dispose();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Oops something went wrong. Error: " + ex.Message);
}
}
}
This is how I would write a quick version of what you wanted. Now, it might not help you out with your issue but it fixes some of the more obvious issues that might come up.
The Try and Catch block are there just for basic error handling to let the user know something went wrong.
The SqlDataReader is enough to notify you if a user with the given parameters exists in the database.
The check you used before
if (Dt.Rows.Count == 1)
{
//...
}
would fail to trigger if your query returned more than 1 row, which should not happen if the Table is created correctly. Check for duplicate entries in your table.
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can I insert and save data into the database using Visual Studio and C#?
This code throws an error. Anyone please give the suggestion to me to solve the error.
image description
At first make sure your the data type of different column of customer table.
Then make sure what type of data you have to save for combobox.
you have to get the selected value from your Combobox. combobox1,combobox2,combobox3 retuns only the class name
System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
You can follow this example
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query):
Specifically, you don't need a reader for an insert statement as it doesn't return a result set.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var sql = "insert into dbo.customer ...";
using (var con = new SqlConnection(ss))
{
var cmd = new SqlCommand(sql , con);
con.Open();
cmd.ExecuteScalar();
MessageBox.Show("Welcome to our gym");
}
}
Hi check that customer table is available in gym Database.
else try this link
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(#name,#weight,#height,#add_class,#gender,#fees)", con);
cmd.Parameters.AddWithValue("name", this.textBox1.Text);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I found that your connection string declaration is wrong
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
need to update like below
public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";
Data source will be not be D, It should be Server name.
enter image description here
I have the database updating with the UserName of the person who uploaded a file and am trying to retrieve only the files the current user uploaded, to display in the gridview.
The page displays the current user name and when that person uploads a file everything is fine. Though when that user hits the search button, all records show up and I get the error:
Error:Invalid column name 'test'
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataReader reader;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM UserUpload WHERE UserName = #un";
command.Parameters.Add(new SqlParameter("#un", UN));
command.Connection = conn;
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Change this line
string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;
to
string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);
you want to match to username as string strings are being wrapped in '' in SQL
If you would be matching by number it would work fine as numbers do not have this requirement.
UPDATE to UPDATE:
Change to something like this (untested)
SqlCommand com = new SqlCommand(UserSearch, conn);
{ DataSet ds = com.ExecuteReader();
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();
}
You would benefit from reading this
Use Parameters instead of assinging the Value to the query string
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString(); ;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string UserSearch = "SELECT * FROM UserUpload WHERE UserName = #un";
SqlCommand com = new SqlCommand(UserSearch, conn);
com.Parameters.Add(new SqlParameter("#un", UN));
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
i have registration page and i want to check that username is already exist in database or not in 3 tier architecture.
MyRegistration.cs:
public static int checkusername(string user_txt)
{
int id2 = 0;
string selectstr = "select * from xyz where UserName = '" + user_txt + " ' ";
id2 = DataAccessLayer.ExecuteReader(selectstr);
return id2;
}
and the code behind onclick event of textbox:
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
int id = xyz.checkusername(txt_username.Text.Trim());
if (id > 0)
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
DataAccessLayer:
public static int ExecuteReader(string Query)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = Query;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
I have edited some of your codes try like below... it will help you...
Text change Event :
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
if (xyz.checkusername(txt_username.Text.Trim()))
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
Check Username :
public bool CheckUsername(string user_txt)
{
bool Result;
Result = DataAccessLayer.ExecuteReader(user_txt);
return Result;
}
Excute Reader :
public bool ExecuteReader(string user_txt)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
SqlCommand cmd = new SqlCommand("select * from xyz where UserName = #UserID", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#UserID";
param.Value = user_txt;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
return true;
else
return false;
}
Usually if the "select query" doesn't find a userName with the parameter user_txt you'll id2 will be end up with the value -1. So the appropriate code would be:
if (id ==-1)
{
lblStatus.Text = "UserName Available";
}
if (id>0)
{
lblStatus.Text = "UserName Already Taken";
}
By the way, your code is highly insecure and your database can be easily attacked using SQL Injection I'd recommend you to understand this issue and add parameters to the query to prevent it. C# has its ways to implement this. Don't try to fix the access to the database, just start from scrath keeping in mind SQL Injection.
As others have mentioned, this approach has potentially serious security issues.
However, your problem may lie here user_txt + " ' ". The spaces around the second ', specifically the one before it may lead to the usernames not matching as expected.
I am trying to make a windows Form Application with a login screen,Form3 Will open Form1 if the username and password are correct.
The code is linked to a database
The code is as follows:
private void button1_Click(object sender, EventArgs e)
{
string u_id = textBox1.Text;
string u_pwd = textBox2.Text;
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXXX.ac.uk;Initial Catalog=mmt12-186;User ID=XXXXXX;Password=XXXXXX");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ("SELECT * FROM UsersData WHERE User = '" + textBox1.Text + "'");
cmd.Parameters.AddWithValue("un", u_id);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() == false)
{
label3.Text = "Invalid Username or Password !";
return;
}
string realpwd = reader.GetString(0);
if (u_pwd == realpwd)
{
Form1 formload = new Form1();
formload.Show();
}
}
Every time I run this code, I get an exception on with the line:
string realpwd = reader.GetString(0);
The exception is:
Invalid attempt to read when no data is present.
The UsersData table has 3 columns, Id, User, Password
Thanks goes to "Alfred Sanz" who answered the question, the problem now is that no error is present but no data is shown, as if the button1_click has no method, the current code is:
private void button1_Click(object sender, EventArgs e)
{
string u_id = textBox1.Text;
string u_pwd = textBox2.Text;
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XX.XXX.ac.uk;Initial Catalog=XXXXXXX ;User ID=XXXX;Password=XXXXX");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ("SELECT * FROM UsersData WHERE User = #un");
cmd.Parameters.AddWithValue("#un", u_id);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
if (reader["Password"].ToString() == u_pwd)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
you already set the value of USER as '" + textBox1.Text + "'" but you are also setting a value cmd.Parameters.AddWithValue("un", u_id); which really does not exist, change your code into
cmd.CommandText = "SELECT * FROM UsersData WHERE User = #un";
cmd.Parameters.AddWithValue("#un", u_id);
and also you can change the reader part to:
while (reader.Read())
{
if (reader["Password"].ToString() == u_pwd.Text
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}