I have a text box that retrieve email from membership table in database. User may edit their email and update the new email. My question is, how to replace the old email with the new one? What is the query for sql?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into aspnet_membership("i dont know how whether to write all columns or only email);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", Textbox2.Text);
My question is, how to replace the old email with the new one?
You need an UPDATE in this case, instead of an INSERT:
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET
email = #email WHERE userID = #userID", conn);
It will work like any other simple update SQL Query:
update TableName set Columname = #Value where Username = #Value
Try this:
You may need UserId, and new Email to replace existing email address for the given existing user.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET email = #newEmail WHERE UserID = #userID");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", Textbox2.Text);
cmd.Parameters.AddWithValues("#UserId", YourUserId);
conn.open();
cmd.ExecuteNonQuery();
conn.close();
you need to use update query and not insert query.
see syntax here:
http://www.w3schools.com/sql/sql_update.asp
check this link from MSDN http://msdn.microsoft.com/en-us/library/ms186862.aspx
SELECT REPLACE('abcdefghicde','cde','xxx');
GO
As you want to Update EmailID so your query should be
SqlCommand cmd = new SqlCommand("Update aspnet_membership set email=#email where UserID=#UserID");
This should work for you, because your Insertquery which you are trying, this will always insert a new record instead of updating older records..
Related
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";
I used following code for deleting record from my SQL server database but this query deleted all my records. I want to delete just the selected row, not all of them.
SqlCommand cmd = new SqlCommand("DELETE FROM tablename WHERE id=id ", con);
cmd.ExecuteNonQuery();
You should transfer param id, my friend. Refer the code below:
var Id = ""; //set the value that you want to delete
SqlCommand cmd = new SqlCommand("DELETE FROM tablename WHERE id=#Id ", con);
command.Parameters.AddWithValue("#Id", Id);
cmd.ExecuteNonQuery();
I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);
I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this.
Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName = ????? usernames????? ", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["text"].ToString());
}
How can I fix this code?
"SELECT FName FROM Users WHERE FName = #paramUsername"
and then you insert the parameter into the cmd like so:
cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";
Check this out:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string validationQuery = "SELECT * FROM Users WHERE FName = #name";
SqlCommand validationCommand = new SqlCommand(validationQuery, connection);
validationCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (!validationReader.Read())
{
string insertQuery = "INSERT INTO Users (FName) VALUES (#name)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
connection.Close();
}
else
{
//Uh oh, username already taken
}
validationReader.Close();
validationCommand.Dispose();
Things to note:
Use parameters, avoid concatenating strings because it's a security vulnerability
Always Close and Dispose your ADO objects
I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query