Upper Function Input parameter in Oracle - sql

I try to prevent SQL injection in SQL query. I used following code to do it but unfortunately I faced some problem. The query is not running in oracle DB:
strQuery = #"SELECT PASSWORD FROM IBK_USERS where upper(user_id) =upper(:UserPrefix) AND user_suffix=:UserSufix AND STATUS_CODE='1'";
//strQuery = #"SELECT PASSWORD FROM IBK_CO_USERS where user_id = '" + UserPrefix + "' AND user_suffix='" + UserSufix + "' AND STATUS_CODE='1'";
try
{
ocommand = new OracleCommand();
if (db.GetConnection().State == ConnectionState.Open)
{
ocommand.CommandText = strQuery;
ocommand.Connection = db.GetConnection();
ocommand.Parameters.Add(":UserSufix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserSufix"].Value = UserSufix;
ocommand.Parameters.Add(":UserPrefix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserPrefix"].Value = UserPrefix.ToUpper();
odatareader = ocommand.ExecuteReader();
odatareader.Read();
if (odatareader.HasRows)
{

Your parameters shouldn't contain the semicolon :. This is just an indicator in your query that the variable that follows is a parameter, but you don't have to supply that on the .NET side:
ocommand.Parameters["UserSufix"] = ...

Related

Go over a simple quote in a Where of a SQL query

I have a SQL query where I have to pass a string in my where, my string can have a simple quote in the name of the program and at the same time break the string and create an error in my request.
Yes I would just like to skip the code, but the actual logic has been done so that we are able to modify the code, so I can't just trust that.
Here is the query in my ASP.NET MVC 5 project:
IQueryable<ListeProgrammesCol> query = db.Database.SqlQuery<ListeProgrammesCol>(
"SELECT id AS offreID, nomProgramme AS nom, codeProgramme AS code, dateAjout, dateLastUpdate, gestionEnLigne " +
"FROM tbl_offreCol " +
"WHERE FK_etablissement = " + instId +" AND offreType = 3 AND archive = 0 AND codeProgramme = '" + code + "' AND nomProgramme = '" + progNom + "' " +
"ORDER BY nomProgramme").AsQueryable();
And here is the query if you want to text in SQL Server Management Studio:
SELECT
id AS offreID, nomProgramme AS nom, codeProgramme AS code,
dateAjout, dateLastUpdate, gestionEnLigne
FROM
tbl_offreCol
WHERE
FK_etablissement = 923000
AND offreType = 3
AND archive = 0
AND codeProgramme = '351.A0'
AND nomProgramme = 'RAC en Techniques d'éducation spécialisée'
ORDER BY
nomProgramme
This is the problem: d'éducation
//////UPDATE
I decided to use linq to make my request, so I no longer need to use quotes. Here is the query:
var query = (from oc in db.tbl_offreCol
where oc.FK_etablissement == instId
&& oc.offreType == 3
&& oc.archive == 0
&& oc.codeProgramme == code
&& oc.nomProgramme == progNom
select new ListeProgrammesCol
{
offreID = oc.id,
nom = oc.nomProgramme,
code = oc.codeProgramme,
dateAjout = oc.dateAjout,
dateLastUpdate = oc.dateLastUpdate,
gestionEnLigne = oc.gestionEnLigne
}).OrderBy(x => x.nom).AsQueryable();

ORA-00933: oracle 8i

I want to use join in Oracle 8i. I have my query as below.
I have this query of getting data from two tables using an join, but I get the error SQL command not properly ended.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID," +
" DLOG.RELEASEID AS RELEASE_BUILD," +
" TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE," +
" DLOGDET.DEPLOYREQUEST AS BAAR_RFD," +
" DLOG.FILENAMEEXT_VC AS SCRIPT_NAME," +
" DLOG.VERSION," +
" DLOG.REQUEST," +
" DLOG.NOTE AS COMMENTS" +
" FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET" +
" JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO;";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
My target is to insert records into a table.
Keep everything in one set of " and also you only need a single ; to end the SQL query outside of the double quotes.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID,
DLOG.RELEASEID AS RELEASE_BUILD,
TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE,
DLOGDET.DEPLOYREQUEST AS BAAR_RFD,
DLOG.FILENAMEEXT_VC AS SCRIPT_NAME,
DLOG.VERSION,
DLOG.REQUEST,
DLOG.NOTE AS COMMENTS
FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET
JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
Oracle 8i did not support standard ANSI SQL JOIN syntax.
That feature was introduced in Oracle 9i Release 2 (aka Oracle 9.2)
Quote from the chapter "What's New in SQL Reference"
SELECT [...] has new ANSI-compliant join syntax.
Don't combine the, strings put all in one.

MS SQL Invalid column name error

This code returns the following error:
"System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'a51'"
a51 is the correct value inside of the record I'm looking for in the EstablishmentCode column of the Establishments table. Account ID is used to find all entries on the Establishments table with that account ID and populate a dataset with Establishment Code values. Account ID value comes from a session variable. Then I use each of these values in a loop where each iteration calls a datareader while loop. Hope I explained this clearly, but I would gladly clarify more if needed. Here's my code.
myConnection.Open();
SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection);
da = new SqlDataAdapter(getEst);
ds = new DataSet();
da.Fill(ds);
int maxrows = ds.Tables[0].Rows.Count;
for (int x = 0; x < maxrows; x++)
{
getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection);
myReader = getPhones.ExecuteReader();
while (myReader.Read())
{
Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>");
Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>");
Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>");
Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>");
Response.Write("<section class='flex phoneButtonSection'>");
Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>");
Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>");
Response.Write("</section>");
Response.Write("</section>");
}
myReader.Close();
}
myReader.Close();
myConnection.Close();
String literals in SQL are denoted by single quotes ('s) which are missing for your value:
getPhones = new SqlCommand
("SELECT * " +
"FROM DispatcherPhones
"WHERE EstablishmentCode = '" +
// Here -------------------^
ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString() +
"'" // And here
, myConnection);
Mandatory comment: concatinating strings in order to create SQL statements may leave your code exposed to SQL injection attacks. You should consider using prepared statements instead.

SQL: Update does not affect any row

I want to update a dataset in a DB2/AS400 table.
The problem is if I there is string parameter in the parameters list the command does not find a row to update.
For example: If I run the command only with the company number the command will succeed. If I run the command with the company number and facility number the command fails.
Does anyone have any idea?
IDbConnection cn = Tools.GetCnApp();
try
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("UPDATE " + Tools.GetSchemeApp() + "/ChangeReasonAssignments");
sql.AppendLine(" SET Confirmed = #CONF, Confirmed_By = #CONFBY, Confirmed_At = #CONFAT");
sql.AppendLine(" WHERE Company = #CONO AND Facility = #FACI AND Department = #DEPT");
sql.AppendLine(" AND Production_Group = #PRGR AND Manufacturing_Order = #ORDR AND Order_Operation = #OPER");
sql.AppendLine(" AND Confirmed = 0");
IDbCommand cmd = cn.CreateCommand();
cmd.SetParameter("#CONO", this.CompanyNumber);
cmd.SetParameter("#FACI", this.FacilityNumber);
cmd.SetParameter("#DEPT", this.ProductionGroup.Department.Name);
cmd.SetParameter("#PRGR", this.ProductionGroup.Name);
cmd.SetParameter("#ORDR", this.ManufacturingNumber);
cmd.SetParameter("#OPER", this.OperationNumber);
cmd.SetParameter("#CONFBY", Base.User);
cmd.SetParameter("#CONFAT", DateTime.Now.ToString());
cmd.SetParameter("#CONF", 1);
cmd.CommandText = sql.ToString();
if (cmd.ExecuteNonQuery() > 0)
{
}
EDIT
The datatypes in database are:
Company: INTEGER
Facility: VARCHAR
Dpartment: VARCHAR
Production_Group: VARCHAR
Manufacturing_Order:INTEGER
Order_Operation: INTEGER
The datatypes in .NET are:
CompanyNumber: int
FacilityNumber: String
Departmentname: String
ProductionGroup: String
Manufacturingorder: int
OrderOperation: int
sql.ToString() results:
UPDATE TSAEDBDEV/ChangeReasonAssignments SET Confirmed = #CONF, Confirmed_By = #CONFBY, Confirmed_At = #CONFAT WHERE Company = #CONO AND Facility = #FACI AND Confirmed = 0
Try to set the string values into ': cmd.SetParameter("#DEPT", "'" + this.ProductionGroup.Department.Name + "'");

MS-Access: SQL UPDATE syntax error, but why?

I'm getting a syntax error in this SQL, and can't seem to figure out why?
The SQL UPDATE returns this on the error:
UPDATE Tankstationer
SET Long='12.5308724', Lat='55.6788735'
WHERE Id = 2;
Here's my code:
foreach (var row in reader)
{
var id = reader.GetInt32(0);
var adress = reader.GetString(1);
var zip = reader.GetDouble(2);
var city = reader.GetString(3);
var adressToParse = adress + " " + zip + " " + city;
GMapGeocoder.Containers.Results result = Util.Geocode(adressToParse, key);
foreach (GMapGeocoder.Containers.USAddress USAdress in result.Addresses )
{
var google_long = convertNumberToDottedGoogleMapsValid(USAdress.Coordinates.Longitude);
var google_lat = convertNumberToDottedGoogleMapsValid(USAdress.Coordinates.Latitude);
Message.Text = "Lattitude: " + google_long + System.Environment.NewLine;
Message.Text = "Longitude: " + google_lat + System.Environment.NewLine;
string updatesql = "UPDATE Tankstationer SET Long='" +google_long+ "', Lat='" +google_lat+ "' WHERE Id = " +id+"";
OleDbCommand update = new OleDbCommand();
update.CommandText = updatesql;
update.Connection = conn;
reader = update.ExecuteReader();
Message.Text = "Done";
}
}
The error is probably because you are executing a reader, but your query does not return anything. Call update.ExecuteNonQuery() instead.
"Long" is a reserved word in Access. If you can't change the schema to call that column something else, put it in brackets:
UPDATE Tankstationer
SET [Long]='12.5308724', Lat='55.6788735'
WHERE Id = 2;
try using update.ExecuteNonQuery() instead of reader.
Saw other comments too late.
I don't use access often, but mine it's using <"> for text delimiter, not <'>
Try:
"id" is being set to Int32 (var id = reader.GetInt32(0);) but you are concatenating it to a string (WHERE Id = " +id+"";). Make sure that id is cast as a string value and not an int.