Insert value locating particular column in Microsoft SQL server - sql

I want to insert value locating particular column. I used following script.
"INSERT INTO tbl_user VALUES(UserID = '" + myUser.ID + "', UserName = '" + myUser.Name + "', Password = '" + myUser.Password + "', UserType = '" + myUser.Type + "')";
But it gives me the following error.
Incorrect syntax near '='.
There may some other way to do this task. But I want to do it in this way. Can I?

Always use parameterized query anyway correct your current attempt as below
"INSERT INTO tbl_user (UserID, UserName, UserName , UserType)
VALUES('" + myUser.ID + "','" + myUser.Name + "', '" + myUser.Password + "', '" + myUser.Type + "')";
RECOMMENDED Way is to Go with parameterized query always to prevent SQL Injection Attacks
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_user (UserID, UserName, UserName , UserType)
VALUES (#UserID,...)", connections)
cmd.Parameters.AddWithValue("#UserID", myUser.ID)
...

No, you can't do it your way.
It is:
INSERT INTO table (column1_name,... ) VALUES (column1_value,...) ;
https://www.techonthenet.com/sql_server/insert.php

Related

Do you know how to fix this UPDATE issue?

When this code runs, I get an UPDATE writing error. Does anybody know what the problem is, and how to fix it?
This is the code:
string sql2 = "UPDATE ezuser";
sql2 += " SET fname = '" + Request.Form["fname"]+ "'";
sql2 += " , lname = '" + Request.Form["lname"] + "'";
sql2 += " , fav = '" + Request.Form["fav"] + "'";
sql2 += " , pw = '" + Request.Form["pw"] + "'";
sql2 += " , order = '" + Request.Form["order"] + "'";
sql2 += " WHERE email = '" + Request.Form["email"] + "'";
MyAdoHelper.DoQuery(fileName, sql2);
Eventhough the question doesnt tell me much about the datatypes of columns, the only thing I could suspect here is the order column, which might be of integer datatype and you might be passing string to that.
Additional note: your code looks very much vulnerable to sql injections. Please take a look into that as well.
At least in SQL Server, order is a reserved keyword and needs to properly quoted if used literally as a column name. Like so:
sql2 += " , [order] = '" + Request.Form["order"] + "'";
As sabhari already mentioned, you need to learn about SQL Injection and how to properly guard against that. Research parametrized statements for the programming language you are using.

Needs to handle the names which has a quotation inside

I have two queries which inserts and updates the DB-
insertSQL = "insert into LineManager(LINEMANAGERID,LINEMANAGERNAME,BUSINESSGROUPID,STATUS) VALUES('" + lineManager.getLineManagerID() + "','" + lineManager.getLineManagerName() + "','" + lineManager.getBusinessGroupID() + "','" + lineManager.getStatus() + "')";
updateSQL = "update LineManager set BUSINESSGROUPID ='" + lineManager.getBusinessGroupID() + "' , LINEMANAGERNAME ='" + lineManager.getLineManagerName() + "' , STATUS ='" + lineManager.getStatus() + "' where LINEMANAGERID='" + lineManager.getLineManagerID() + "'";
so far it was working fine for the regular names, but it is facing issues when the LineManager name is like -'Doko N'dah, Mr. Dominick'. It's throwing exceptions during execution.
Can anybody help to resolve this issue?
Use bind variables:
QSqlQuery query;
query.prepare("insert into LineManager(LINEMANAGERID,LINEMANAGERNAME,BUSINESSGROUPID,STATUS) VALUES(:id,:name,:groupid:status)");
query.bindValue( ":id", lineManager.getLineManagerID() );
query.bindValue( ":name", lineManager.getLineManagerName() );
query.bindValue( ":groupid", lineManager.getBusinessGroupID() );
query.bindValue( ":status", lineManager.getStatus() );
query.exec();

I am getting this error while executing update query in visual studio 2012

Incorrect syntax near '='
my code is
"update staff_Tables
set emp_id='" + txtEmployeeID.Text + "' ,
emp_sal='" + txtEmpSal.Text + "',
emp_name='" + txtEmployeeName.Text + "',
emp_Deignation='" + txtDesignation.Text + "',
Gender='" + cboGender.Text + "',
contactno='" + txtContact.Text + "',
Address='" + rtbAddress.Text + "',
Joining_Date='" + txtjoindate.Text + "'
where txtid=" + txtid.Text, sqlcon.getCon());
First, you should never concatenate sql queries like this.
Your query is extremely vulnerable to Sql Injection attacks.
Always use either stored procedures or parameterized queries.
Second, did you try to debug? judging by the column names, Emp_Id, Emp_Sal and contactno are probably numeric data and not strings, therefor the ' surrounding the values is wrong.
Your query should look like this:
"update staff_Tables
set emp_id = #emp_id,
emp_sal = #emp_sal,
emp_name = #emp_name,
emp_Deignation = #emp_Deignation,
Gender = #Gender,
contactno = #contactno,
Address = #Address,
Joining_Date = #Joining_Date
where txtid = #txtid"
and you add the parameter to the SqlCommand.Parameters collection like this:
cmd.Parameters.Add("#emp_id, SqlDBType.Int).Value = txtEmployeeID.Text
You probably have a single quote in one of your .Text values, fix by doubling them up, example:
Address='" + Replace(rtbAddress.Text, "'", "''") + "' vb
Address='" + rtbAddress.Text.Replace("'", "''") + "' #c
But yes, you are open to sql injection with this method of updating database.

update query is giving an error

I have written a c# code to update a MS Access table data, but it is showing an error "Syntax error in update statement".
string sql = "update Users set Name='" + txtUser_Name.Text + "',Password='"
+ txtPassword.Text + "'where Name='" + usr + "'";
Please tell me the right code.
Maybe this will work
string sql = "update Users set Name='" + txtUser_Name.Text +
"', Password='" + txtPassword.Text + "' where Name='" + usr + "'";

string concatation in sql query

i am having confusion with this string concatenation
could some body please brief me how this string concatenation taking place?
The confusion i am having is that, how this +, "", ' are working in this
int i = Magic.Allper("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Anything between two " characters is taken as a String in Java so "','" produces ','. SQL requires Strings wrapped in '. So "'" + venueTxt.Text + "'" parses to 'variable value' when the query is made.
("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Assuming that
Label1= Hello
companyTxt = ABC
txtBranch = Engineering
dateTxt = 2010-12-01
reportingTxt = Fergusson
venueTxt = Batcave
eligibilityTxt = No
The above values are replaced in the SQL statement, making it look like
("insert into tbl_notice values ('" + Hello + "','" + ABC + "','" + Engineering + "','" + 2010-12-01 + "' ,'" + Fergusson + "','" + Batcave + "','" + No + "')");
The "+" operator joins the string values, resulting in
("insert into tbl_notice values ('Hello','ABC','Engineering','2010-12-01' ,'Fergusson','Batcave','No')")
I strongly recommend that you don't use string concatenation in SQL queries. They provoque SQL injections. This will cause security issues.
What is SQL Injection?
In response to your question, this concatenation simply takes every TextBox.Text property value and concatenate it into your insert statement.
I strongly recommend that you're using parameterized queries using ADO.NET lise the following example (assuming SQL Server):
using (var connection = new SqlConnection(connString))
using (var command = connection.CreateCommand()) {
string sql = "insert into tbl_notice values(#label1, #companyTxt, #txtBranch, #dataTxt, #reportingTxt, #venueTxt, #eligibilityTxt)";
command.CommandText = sql;
command.CommandType = CommandType.Text;
SqlParameter label1 = command.CreateParameter();
label1.ParameterName = "#label1";
label1.Direction = ParameterDirection.Input;
label1.Value = Label1.Text;
SqlParameter companyTxt = command.CreateParameter();
companyTxt.ParameterName = "#companyTxt";
companyTxt.Direction = ParameterDirection.Input;
companyTxt.Value = companyTxt.Text;
// And so forth for each of the parameters enumerated in your sql statement.
if (connection.State == ConnectionState.Close)
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
I would use the string.Format method for clarity
int i = Magic.Allper(string.Format("insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));
You might also want to create an extension method that will make sure the strings are safe to pass to SQL in this fashion
public static string ToSqlFormat(this string mask, params string[] args)
{
List<string> safe = args.ToList();
safe.ForEach(a => a.Replace("'", "''"));
return string.Format(mask, safe);
}
which will let you write
string insert = "insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
int i = Magic.Allper(insert.ToSqlFormat(
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));