I have done that before, but in this case I have an insert into table query where value of the column of the target table comes as a result from another query. Having that, I'm not sure if my parametarized query is formatted the right way.
Here is an original query without before Sql Injection fix:
cmd.CommandText += "insert into controlnumber (controlnumber, errorid)
values ('" + ControlNumber + "', (select errorid from error where
errordescription = '" + ErrorDescription + "' and errortype = '" +
ErrorType + "' + and applicationid = " + ApplicationID + " and statusid =
" + StatusID + " and userid = " + UserID + " and errortime = '" +
ErrorTime + "');";
This is the query after I tried to fix Sql Injection:
cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
values (#ControlNum, (select errorid from error where errordescription =
#ErrorDescription and errortype = #errorType and applicationid =
#ApplicationID and statusid = #StatusID and userid = #UserID and
errortime = #ErrorTime)"
This is where I add parameters:
.....
command.CommandType = CommandType.Text
command.Parameters.AddWithValue("#ErrorDescription ", ErrorDesc);
command.Parameters.AddWithValue("#ControlNum", cntNumber);
command.Parameters.AddWithValue("#errorType",ErrorType);
command.Parameters.AddWithValue("#ApplicationID",AppID);
command.Parameters.AddWithValue("#StatusID",StatusID);
command.Parameters.AddWithValue("#UserID",UserID);
....
I'm just wondering if my CommandText is formatted the right way.
Thank's
try this:
cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
select #ControlNum, errorid from error where errordescription =
#ErrorDescription and errortype = #errorType and applicationid =
#ApplicationID and statusid = #StatusID and userid = #UserID and
errortime = #ErrorTime)"
When using INSERT INTO SELECT FROM, you do not use keyword VALUES. The syntax is:
INSERT INTO TABLE(columns) SELECT ... FROM TABLE2
Related
Im trying to avoid using native query. I have this query that uses the filter function, how could I rewrite this to not use that and work in regular jpql?
#Query(
"SELECT time_bucket(make_interval(:intervalType), d.time) as groupedDate, " +
"CAST(d.team_Id as varchar) as teamId, CAST(d.service_Id as varchar) as serviceId, CAST(d.work_id as varchar) as workId, " +
"ROUND(CAST(count(d.value) filter ( where d.type = 'A') AS numeric) /" +
" (CAST(count(d.value) filter ( where d.type = 'B') AS numeric)), 4) as total " +
"FROM datapoint d " +
"WHERE d.team_Id = :teamId and d.service_id in :serviceIds and d.work_id = :workspaceId and d.type in ('A', 'B') " +
"AND d.time > :startDate " +
"GROUP BY groupedDate, d.team_Id, d.service_Id, d.workspace_Id " +
"ORDER BY groupedDate DESC",
nativeQuery = true
)
in the FROM statement you have to use the DAO object instead of the table name
This code return empty cursor.What is wrong here?
Data is already there in sqlitedb.
public static final String COL_2 = "ID";
public static final String COL_3 = "TYPE";
public Cursor checkData(String id, String type){
SQLiteDatabase db = getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = " + id+ " AND " + COL_3 + " = " + type , null);
return res;
}
When you pass strings as parameters you must quote them inside the sql statement.
But by concatenating quoted string values in the sql code your code is unsafe.
The recommended way to do it is with ? placeholders:
public Cursor checkData(String id, String type){
SQLiteDatabase db = getWritableDatabase();
String sql = "SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = ? AND " + COL_3 + " = ?";
Cursor res = db.rawQuery(sql , new String[] {id, type});
return res;
}
The parameters id and type are passed as a string array in the 2nd argument of rawQuery().
I finally solved it.
public Cursor checkData(String id, String type){
SQLiteDatabase db = getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = '" + id+ "' AND " + COL_3 + " = '" + type +"'" , null);
return res;
}
if COL_3 type is string try this:
Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = " + id+ " AND " + COL_3 + " = '" + type + "'" , null);
How I convert this sql query :
Select ID, first_name, last_name, phone_number, room_type, room_floor, room_number, break_fast, lunch, dinner, cleaning, towel, s_surprise, supply_status, food_bill
from reservation
where check_in = '" + "True" + "' AND supply_status= '" + "False" + "'"
into LINQ
You can try something similar to this:
var rows = from r in reservation
where r.check_in == "True" && r.supply_status == "False"
select r;
I have a sub form with staff records on it within a main form. I am trying to allow the user to select a record from the sub form and add it to a table, here is my code which, to me, looks correct. However it gives me an error saying "Syntax error in INSERT INTO"
Private Sub Command3_Click()
Dim dbs As Database
Dim sqlstr As String
Set dbs = CurrentDb
Forename = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_forename, "")
Surname = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_surname, "")
emp_no = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_empno, "")
CAP_ID = Forms!frm_Capex_Submission!CAP_ID
sqlstr = "INSERT INTO tbl_CapexStaff ( Forename, Surname, EmployeeID, CAP_ID) )" _
& " SELECT '" & Nz(Me!shy_forename, "") & "' AS Expr1, '" & Nz(Me!shy_surname, "") & "' AS Expr2, '" & Nz(Me!shy_empno, "") & " AS Expr3, " & Forms!frm_Capex_Submission.CAP_ID & " as expr4, """
dbs.Execute (sqlstr)
tbl_CapexStaff.Requery
End Sub
There is an extra ")" in your query
INSERT INTO tbl_CapexStaff ( Forename, Surname, EmployeeID, CAP_ID) )
I have a C# console application that uploads data into SQL Server database after doing a bit of calculation which is done using various C# functions. Now the problem is it is taking almost 1 sec to calculate and upload one line of data and I have to upload 50,000 lines of data in the same way.
Please suggest me a way to solve this problem.
P.S. : I am using stringbuilder to compose separate insert statements and upload in bulk. This process is taking only 1 min.
Inserting or updating to database is hardly taking any time as I have mentioned in my question. Calculation is taking most of the time. I am attaching the code sample of a function below:
public void EsNoMinLim()
{
ds = new DataSet();
ds = getDataSet("select aa.Country, aa.Serial_No from UEM_Data aa inner join (select distinct " +
"IId, Country from UEM_Data where Active_Status is null) bb on aa.iid = bb.iid where aa.Serial_No <> '0'").Copy();
execDML("Delete from ProMonSys_Grading");
StringBuilder strCmd = new StringBuilder();
foreach (DataRow dRow in ds.Tables[0].Rows)
{
SiteCode = dRow["Country"].ToString();
Serial_No = dRow["Serial_No"].ToString();
ds_sub = new DataSet();
ds_sub = getDataSet("select EsNo_Abs_Limit from EsNo_Absolute_Limit where Fec_Coding_Rate in "+
"(select MODCOD from FEC_Master where NMS_Value in (select Top 1 FEC_Rate from "+
"DNCC_Billing_Day where Serial_No = '" + Serial_No + "' and [Date] = (select max([Date]) "+
"from DNCC_Billing_Day where Serial_No = '" + Serial_No + "')))").Copy();
if (ds_sub.Tables[0].Rows.Count > 0 && Convert.ToString(ds_sub.Tables[0].Rows[0][0]) != "")
{
Min_EsNo = Convert.ToString(ds_sub.Tables[0].Rows[0][0]);
}
else
{
Min_EsNo = "a";
}
if (Min_EsNo != "a")
{
ds_sub = new DataSet();
ds_sub = getDataSet("select Top 1 modal_Avg_EsNo from DNCC_Billing_Day where " +
"Serial_No = '" + Serial_No + "' and [Date] = (select max([Date]) from DNCC_Billing_Day " +
"where Serial_No = '" + Serial_No + "')").Copy();
if (ds_sub.Tables[0].Rows.Count > 0 && Convert.ToString(ds_sub.Tables[0].Rows[0][0]) != "")
{
Avg_EsNo = Convert.ToString(ds_sub.Tables[0].Rows[0][0]);
}
else
{
Avg_EsNo = "-1";
}
ds_sub = new DataSet();
ds_sub = getDataSet("select Top 1 Transmit_Power from ProMonSys_Threshold where Serial_No = '" + Serial_No + "'").Copy();
if (ds_sub.Tables[0].Rows.Count > 0 && Convert.ToString(ds_sub.Tables[0].Rows[0][0]) != "")
{
Threshold_EsNo = Convert.ToString(ds_sub.Tables[0].Rows[0][0]);
}
else
{
Threshold_EsNo = "-1";
}
getGrade = EsNoSQFGrading(Min_EsNo, Avg_EsNo, Threshold_EsNo);
strCmd.Append("insert into ProMonSys_Grading(SiteCode, Serial_No, EsNo_Grade) " +
"values('" + SiteCode + "','" + Serial_No + "','" + getGrade + "')");
}
}
execDML_StringBuilder(strCmd);
}
Find out, what part of the process is the expensive one. Use StopWatch to check how long loading, calculating and saving takes separately. Then you which part to improve (and can tell us).