Can I use where condition in Insert statement????
I have coded like this, its showng me an error call MySQLException was unhandled, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE RegistrationID='3'' at line 1. My code:-
MySqlCommand cmd1 = new MySqlCommand("INSERT INTO registration(DueAmount) VALUES ('"+textBox5.Text + "') WHERE RegistrationID='"+textBox2.Text+"'",connection);
You're mixing 2 different statements.
An UPDATE statement updates an existing row in your table.
An INSERT statement adds a new row in your table.
I think you want to use an UPDATE statement and modify an existing row.
MySqlCommand cmd1 = new MySqlCommand("
UPDATE Registration Set DueAmount= '"+textBox5.Text
+ "' WHERE RegistrationID='"+textBox2.Text+"'",connection);
The correct syntax of INSERT doesn't have WHERE clause. I think you want UPDATE instead of INSERT,
UPDATE registration
SET DueAmount = 'txt5'
WHERE RegistrationID = 'txt2'
the only way you can use WHERE in SELECT is when you are using INSERT INTO....SELECT statement.
one more thing, since you are using ADO.NET, make sure that you parameterized your query to avoid SQL Injection, and use USING statement.
string query = "UPDATE registration
SET DueAmount = #dateAmount
WHERE RegistrationID = #RegID"
using (MySqlCommand cmd1 = new MySqlCommand(query,connection))
{
cmd1.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#dateAmount", textBox5.Text);
cmd.Parameters.AddWithValue("#RegID", textBox2.Text);
// other codes
}
INSERT with WHERE doesn't make sense. INSERT always inserts a new row. You might be looking for REPLACE INTO which does a insert if that record doesnt exist or an update if it does based on its primary key.
INSERT puts a new line to database. You can not put a new line WHERE sth is sth. But you can UPDATE it. Hope this helps.
You need to use an UPDATE statement.
tHS SYNTAX IS SIMILAR: "UPDATE registration SET DueAmount = '" + textBox5.Text + "' WHERE RegistrationID='"+textBox2.Text+"'"
You can try with Update
var query = "UPDATE Registration SET DueAmount= $Paremeter1 WHERE RegistrationID = $Paremeter2";
var cmd1 = new MySqlCommand(query, connection);
cmd1 .Parameters.AddWithValue("$Paremeter1", textBox5.Text);
cmd1 .Parameters.AddWithValue("$Paremeter2", textBox2.Text);
Related
I have this database:
Database Image
The database in picture have only CASE_KEY and DEPARTMENT_CASE_NUMBER column, and it doesn't have an ID. What I want to accomplish is to update my database using a TextField.Text without using ID but the problem is I don't know what to put in my Sql Command WHERE clause, because the database doesn't have an ID. Note I am not allowed to put an ID column. This is what I did so far. Please comment what are the alternatives I can use. Thank you.
CODE
connect.Open();
command.CommandText = "UPDATE TV_LABCASE SET DEPARTMENT_CASE_NUMBER = #departmentCaseNumber WHERE //This is my problem";
command.Connection = connect;
command.Parameters.AddWithValue("#departmentCaseNumber", txtDepartmentCase.Text);
command.ExecuteNonQuery();
if the CASE_KEY and the DEPARTMENT_CASE_NUMBER are unique together, that is your ID
You could do something like this:
connect.Open();
command.CommandText = "UPDATE TV_LABCASE SET DEPARTMENT_CASE_NUMBER = #newDepartmentCaseNumber WHERE CASE_KEY = #caseKey AND DEPARTMENT_CASE_NUMBER = #oldDepartmentCaseNumber";
command.Connection = connect;
command.Parameters.AddWithValue("#newDepartmentCaseNumber ", txtDepartmentCase.Text);
command.Parameters.AddWithValue("#caseKey", variableThatContainsThisInfo);
command.Parameters.AddWithValue("#oldDepartmentCaseNumber", variableThatContainsThisInfo);
command.ExecuteNonQuery();
Note that I did change the departmentCaseNumber into newDepartmentCaseNumber
SqlCommand insertCoins = new SqlCommand("UPDATE [Table] SET coins =
#rouletteCoins
WHERE steamid = #userid", cnn);
insertCoins.Parameters.AddWithValue("#rouletteCoins", coins);
insertCoins.Parameters.AddWithValue("#userid", info);
insertCoins.ExecuteScalar();
Trying to send a basic query to the database, it works with insert and select but not with update. Help would be much appreciated.
Use ExecuteNonQuery() instead of ExecuteScalar(). Use this (ExecuteNonQuery) for insert, update and delete statements.
Hello I got a big problem I am trying to add a new column to my MSSQL Database Table and i tried it like thousand times but it wont work.
My destination is to press a button then use the function "eventsspalte_Hinzufügen" to add a new column with the name thats Inserted by the user.
This is the snippet.
private void eventsspalte_Hinzufügen()
{
SQL_eingabe = "ALTER TABLE Teilnahmen_Events ADD #tbName bit NOT NULL ;"; // CONSTRAINT strconst3 DEFAULT 0
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = SQL_eingabe;
cmd.Parameters.AddWithValue("#tbName", tb_Eventname.Text);
cmd.ExecuteNonQuery();
con.Close();
}
The Exception says that cmd.ExecuteQuery() is not able to Execute the sql Command because of the wromg Syntax at #tbName I also tried to use a variable like:
ALTER TABLE Teilnahmen_Events ADD'"+ tb_Eventname.Text +"'bit NOT NULL ;";
but it also didnt work...
I hope you got an solution for me thank you very much.
you cannot pass column name as parameter.
In your second example, single quotes are not needed, so change it into
ALTER TABLE Teilnahmen_Events ADD "+ tb_Eventname.Text +" bit NOT NULL ;";
I'm having problems with my code. I haven't used SQL services at anytime, so its kinda tricky to figure out what's the problem. The main problem is what it says on the title, i get incorrect Syntax when i try to Read, Update or Delete data from SQL database.
Here is the code:
string Connection2 = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AuthMyRegistery\AuthMyRegistery\Data.mdf;Integrated Security=True;User Instance=True";
string Query = "delete from * where idWorkerInfo='" + this.WorkerIdTextBox.Text + "';";
SqlConnection Conn2 = new SqlConnection(Connection2);
SqlCommand Command2 = new SqlCommand(Query, Conn2);
SqlDataReader Reader2;
Conn2.Open();
Reader2 = Command2.ExecuteReader();
MessageBox.Show("Data Deleted");
while (Reader2.Read())
{
}
Conn2.Close();
Issue is here, no table name defined
delete from * where idWorkerInfo=
Should be
Delete From TableName where idWorkerInfo=
'*' isn't a valid target for a delete statement, what table do you want to delete from?
The syntax should be something like
delete from MyTable where idWorkerInfo='abc'
You need to specify the name of table instead of a wildcard.
The basic syntax of the DELETE statement is the following (see the full documentation in MSDN - DELETE (Transact-SQL)):
DELETE FROM table_name
WHERE some_column=some_value;
Moreover, you should not be creating your SQL query using string concatenation (never ever use this in production), as this makes you vulnerable to SQL injection attacks.
Instead, you should be using a parameterized query so that all user input gets properly escaped:
var cmd = new SqlCommand("DELETE FROM MyTable WHERE idWorkerInfo=#id", conn2);
cmd.Parameters.AddWithValue("#id", WorkerIdTextBox.Text);
cmd.ExecuteNonQuery();
The query itself is incorrect.
Consider this:
delete from * where idWorkerInfo='Sth'
You need to replace * with an actual table name.
There is no * in delete ... The syntax of delete is as follows
DELETE FROM table_name
WHERE some_column = some_value;
I am using VS2005 C# ASP.NET and SQL Server 2005.
I have a search function on my asp page and I feel that my SELECT query is vulnerable to SQL injection.
This is my current SELECT statement:
string LoggedInUser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [empUser] LIKE '%"+LoggedInUser+"%'";
SqlDataSource1.DataBind();
*where searchTB is my search text box; DropDownList1 is my search category; and LoggedInUser is the username of the logged in user.
I have implemented parameter instead of concatenation in one of my INSERT statement:
string sql = string.Format("INSERT INTO [TABLE2] (Username) VALUES (#Username)");
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("Username", usernameTB.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
I would like to change my SELECT statement like my INSERT statement, using parameter instead. May I know how should I change it?
Thank you
You can add parameters to your selectcommand using
SqlDataSource s = new SqlDataSource();
s.SelectParameters.Add("paramName", "paramValue");
There are other parameter collections for delete, update and insert too.
s.DeleteParameters
s.UpdateParameters
s.InsertParameters
More Information:
MSDN: SqlDataSource.SelectParameters Property
Programmatically Using SqlDataSource
hope this helps
See Using Parameters with the SqlDataSource Control
And SqlDataSource.SelectParameters Property
You can specify SelectParameters Property for SqlDataSource to use parameterized SQL query
Write a method that gets the data sourse and use sql parameters for the query. Here is a good example how to add parameters in a command object
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
I would use a method for the query so that I separate the Database Access from the UI functionality. Also, this allows to reuse the query.
It's not a straightforward task to dynamically specify a fieldname in query, so I'd suggest just doing switch/case validation for field name, like this:
switch (DropDownList1.Text)
{
case "ValidField1":
case "ValidField2":
...
break;
default:
throw new ArgumentException(...); // or prevent query execution with some other statement
}
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like #value AND [empUser] LIKE #user";
SqlDataSource1.SelectParameters.Add("value", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("user", "%"+LoggedInUser+"%");
SqlDataSource1.DataBind();
You can simply use a filter expression for the SQL datasource SQL Datasource filter expression
You can write your own select function method with object datasource/datatable