This question already has answers here:
SqlCommand INSERT INTO query does not execute
(3 answers)
Closed 7 years ago.
I am using visual studio, i have a connection to an SQL server and im trying to update a table in the database.
I am not recieving any errors nor am i updating anything
Below is the code i have used
protected void Btn1_Click(object sender, EventArgs e)
{
//SQL for insert here.
string MyConnectionString = ConfigurationManager.ConnectionStrings
["testconnect"].ConnectionString;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = MyConnectionString;
myConnection.Open();
SqlCommand cmd = new SqlCommand("insert into Don_Test (ID, Test) values ('" + IDTxt.Text + "','" + TESTTxt.Text + "')", myConnection);
//Call refresh
refreshPage();
myConnection.Close();
}
Actually, you are not executing your query, but just opening connection and closing it later.
Add line of code cmd.ExecuteNonQuery(); before refreshPage().
Also notice - concatenating query text is very bad idea since it leads to SQL injection attack.
Use parameterized query instead.
Related
This question already has answers here:
Error on sql database "Must declare the scalar variable"
(2 answers)
Closed 4 years ago.
I am getting this error when trying to run the code below. Any insight on to what I am doing wrong? I am pretty new to this, and want to get this to work pretty bad. I have gotten zero help from this site so far in a previous question I asked. But decided to give this forum another shot, before giving up on stackoverflow
protected void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection =
new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
"VALUES (#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID), myConnection");
myCommand.Parameters.AddWithValue("#GeneratorName", GenName.Text);
myCommand.Parameters.AddWithValue("#GeneratorAddress", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GeneratorCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GeneratorState", GenState.Text);
myCommand.Parameters.AddWithValue("#GeneratorZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GeneratorPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GeneratorContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GeneratorEPAID", GenEPAID.Text);
myConnection.Open();
myCommand.Connection = myConnection;
myCommand.ExecuteNonQuery();
myConnection.Close();
}
First, Stackoverflow is very helpful :) Don't give up on this platform.
Now for your question:
The parameters your SQL statement is expecting are:
(#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID)
While you later assign them with different names.
It should be:
myCommand.Parameters.AddWithValue("#GenName", GenName.Text);
myCommand.Parameters.AddWithValue("#GenAdd", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GenCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GenState", GenState.Text);
myCommand.Parameters.AddWithValue("#GenZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GenPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GenContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GenEPAID", GenEPAID.Text);
When using #parameter , you must assign a value to a parameter with the same exact name.
This question already has answers here:
How do parameterized queries help against SQL injection?
(6 answers)
Closed 4 years ago.
I'm working on a simple script to query a database based off user input, and I was wondering if there's any chance of injection with something like .net's parameterized queries?
By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.
Here is an example, taken from Here:
private static void UpdateDemographics(Int32 customerID,
string demoXml, string connectionString)
{
// Update the demographics for a store, which is stored
// in an xml column.
string commandText = "UPDATE Sales.Store SET Demographics = #demographics "
+ "WHERE CustomerID = #ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I am currently working on a dummy project in which I am making a login screen. I don't have any big intentions with the project, beside learning some C# and sql.
I am currently trying append a new user to the database which contains each username and their password, but I am for some reason getting an error message.
The entry written in the textbox should be stored in the database, but for some reason is this not happening..
I am getting an error stating I have a syntax error which I am not sure i understand.
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (DbConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (DbCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}
Do not do the following, ever
"INSERT INTO [dbo].[information] (id,password)
VALUES (" + someStringVariable + "," + someOtherStringVariable + ")"
Just think about what you're doing here - you're putting whatever text the user entered directly into your query string. This is the easiest way to have your database dropped or all the information it contains stolen.
Instead, use prepared statements
var commandText = "INSERT INTO [dbo].[information] (id,password) VALUES (#Username, #Password)"
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = create_user_username_textbox.Text
command.Parameters.Add("#Password", SqlDbType.VarChar).Value = create_user_password_textbox.Text
command.ExecuteNonQuery();
}
You should also strongly consider NOT storing passwords in plain text
Updated with suggestion to replace Parameters.AddWithValue - obviously if the column type on your database is different, set it accordingly
The values are strings so the resulting SQL command text should enclose them within single quotes.
VALUES ('"+create_user_username_textbox.Text+"','"...
However, you should really parameterise the query to prevent the potential for Sql injection attacks.
Change the string to:
VALUES (#id,#pw)"))
Add parameters to the command:
command.Parameters.Add(new SqlParameter("#id", create_user_username_textbox.Text));
command.Paramaters.Add(new SqlParameter("#pw", create_user_password_textbox.Text));
try this -
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (SqlConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}
This question already has answers here:
add selected value to users profile
(2 answers)
Closed 9 years ago.
I am trying to write an insert statement where the job is to take selected item the user has selected then insert it into their profile.
I am using Profile provider.
There is a new column I have made in UserProfile table (that stores stuff like username, age and so forth) and I have called it Rented.
e.g.:
User Tom45
rented Pirates of The caribbean
age 23
Could someone let me know if I am doing it right as I can't seem to get it to work.
My Insert and SQL:
protected void Button3_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ASPNetDB.mdb;Persist Security Info=True");
{
da.InsertCommand = new OleDbCommand("INSERT INTO UserProfile (Rented) VALUES (#Rented) WHERE [UserName] = ?", conn);
string dvdrent = DG_Latest.SelectedRow.Cells[1].Text;
OleDbParameter rented = new OleDbParameter();
{
da.InsertCommand.Parameters.AddWithValue("#Rented", DG_Latest.SelectedRow.Cells[2].Text);
}
conn.Open();
da.InsertCommand.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
I have this table:
And each user has a profile:
Once they're logged in they can choose to rent dvds:
The problem is I do not think my query does this, as it does not work.
instead #Render write question mark.
you need add second parameter for the User criteria, and set it.
so:
protected void Button3_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ASPNetDB.mdb;Persist Security Info=True");
{
da.InsertCommand = new OleDbCommand("INSERT INTO UserProfile (Rented) VALUES (?) WHERE [UserName] = ? ;", conn);
da.InsertCommand.Parameters.AddWithValue("#Rented", DG_Latest.SelectedRow.Cells[2].Text);
da.InsertCommand.Parameters.AddWithValue("#User", XXXXXXXXX);
conn.Open();
da.InsertCommand.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
source: msdn
This question already has answers here:
The multi-part identifier "TextBox1.Text" could not be bound in C# ASP.NET?
(3 answers)
Closed 9 years ago.
if (validateEmailId(email))
{
pictureBox5.Visible = true;
SqlConnection con = new SqlConnection("conection string");
SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email=" + email + " WHERE code ='" + textBox2.Text + "' ", con);
cmd2.Connection = con;
cmd2.Connection.Open();
cmd2.ExecuteNonQuery();//line 7
con.Close();
}
validateEmailId is a function which validates the email entered(using regular expression)..
The email entered in the 'email' textbox is validated and is returned to the above function..
When the control passes to line 7 following error is encountered:
The multi-part identifier "sxxx#yahoo.com" could not be bound.
It means sxxx#yahoo.com has passed the validation test, but a problem occurred in line 7.
On the SQL end, the column 'email' has varchar(50) as its data type...I don't think that's an issue....
You should at least put single quotes around the email adress:
SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email='" + email + "' WHERE code ='" + textBox2.Text + "' ", con);
However, this is not a good way of passing in params, as you are leaving this wide open for SQL injection attacks...
A better way would be to use a parameterized query, like this:
SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email=#email WHERE code=#code", con);
cmd2.Parameters.AddWithValue("#email", email);
cmd2.Parameters.AddWithValue("#code", textBox2.Text);
Then you don't need to supply the single quotes, and you're at the same time safeguarding against SQL injection attacks...
Ouch, I smell SQL injection and lack of disposal. Try this:
using (SqlConnection con = new SqlConnection("conection string")) {
using (SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email=#Email WHERE code = #Code", con)) {
cmd2.Parameters.AddWithValue("#Email", email);
cmd2.Parameters.AddWithValue("#Code", textBox2.Text);
con.Open();
cmd2.ExecuteNonQuery();
}
}
The using directives will close the SqlConnection and SqlCommand no matter if they fail or execute properly. The SqlParameters will prevent any form of SQL injection.
Another sidenote: your passing the conn argument to the SqlCommand constructor AND are setting the connection property of the SqlCommand after that, passing the SqlConnection to the SqlCommand already sets the connection property.