MySql Parameter must be defined mvc - mysql

i have this code here:
var sql = "select shr_id, shc_id " +
"from tbox_operational.shipment_ref " +
"inner join tbox_operational.shipment_collo_ref using (shr_id) " +
"where shr_insdtm between ?dateTimeFrom";
var parameters = new List<MySqlParameter> {
new MySqlParameter("?dateTimeFrom", dateTimeFrom.ToString("yyyy/MM/dd HH:mm:ss"))
};
var query = (from db in context.Database.SqlQuery<ShridsModel>(sql, parameters)
select db).ToList();
return query;
But it keeps me getting this error:
{"Parameter '?dateTimeFrom' must be defined."}
i have also in my connection string:
server=xxx;user id=runtime;password=xxxx;AllowUserVariables=True;
What am i doing wrong here?

I have solved...
Instead of passing a list of the parameters, i pass each one individual and he recognizes it all

Related

SQL parametric columns in ASP.NET

Why can you not use parameters in an SQL statement as the column name? I found that out after two hours of thinking what the problem could be. The only way it seemed possible was by doing it in a way it could be vulnerable to SQL injections (which for me wasn't a problem because the parameters are generated serverside).
This works:
string cmdgetValues = "SELECT " + column + " FROM user WHERE " + filterColumn + " = #filter";
MySqlCommand getValues = new MySqlCommand(cmdgetValues, connectionDB);
getValues.Parameters.AddWithValue("#filter", filterValue);
This doesn't work:
string cmdgetValues = "SELECT #column FROM user WHERE #filterColumn = #filter";
MySqlCommand getValues = new MySqlCommand(cmdgetValues, connectionDB);
getValues.Parameters.AddWithValue("#column", column);
getValues.Parameters.AddWithValue("#filterColumn", filterColumn);
getValues.Parameters.AddWithValue("#filter", filterValue);
Why is this? And is it intended?
Because select columns are fundamental query
You can't parameterise the fundamental query, so you have to build the query at the code.
If you want to decide the query columns runtime maybe you can try to use Prepared SQL Statement Syntax in Mysql.

error in LIKE SQL syntax

I'm using nodeJs and mysql package.
I want to use LIKE sql statement with varibale.
this is source code :
var likemobile = '%'+mobile;
var query = "SELECT vtiger_contactaddress.contactaddressid as 'leadid',
vtiger_contactaddress.mobile,
vtiger_contactaddress.phone
FROM `vtiger_contactaddress`
INNER JOIN `vtiger_crmentity`
ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid AND
vtiger_crmentity.deleted=0 AND
vtiger_contactaddress.mobile LIKE "+likemobile+" OR
vtiger_contactaddress.phone LIKE "+likemobile;
and this is error that returns:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual th
at corresponds to your MySQL server version for the right syntax to use near '%8
8436500 OR vtiger_leadaddress.phone LIKE %88436500' at line 1
You need to enclose the like pattern in single quotes.
Two other suggestions:
Only use single quotes for string and date constants (not column aliases).
Use parameterized queries, so you are not putting user input into query strings.
If you indeed are using node-mysql, you should run queries as instructed in the documentation. Assuming you have a connection object already, querying with bind variables becomes simple:
connection.query({
sql : "SELECT vtiger_contactaddress.contactaddressid as leadid, "
+ " vtiger_contactaddress.mobile, "
+ " vtiger_contactaddress.phone "
+ "FROM `vtiger_contactaddress` "
+ "INNER JOIN `vtiger_crmentity` "
+ " ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid"
+ " AND vtiger_crmentity.deleted=0 AND "
+ " (vtiger_contactaddress.mobile LIKE concat('%', ?) OR "
+ " vtiger_contactaddress.phone LIKE concat('%', ?))",
values: [mobile, mobile]
}, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
Things to note here:
Bind variables are used, preventing SQL Injection
The concat function is used for prefixing the (sanitized) input with the wildcard character (%)
The two query conditions that are ORed together are now separated with parenthesis from vtiger_crmentity.deleted=0, which is probably what you want
You need to write the resultset-handling code in the callback function, accessing the data through the results and fields variables
#Gordon Linoff is correct. Somelike this:
var likemobile = mobile;
var query = "SELECT vtiger_contactaddress.contactaddressid as 'leadid', vtiger_contactaddress.mobile, vtiger_contactaddress.phone FROM `vtiger_contactaddress` INNER JOIN `vtiger_crmentity` ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid AND vtiger_crmentity.deleted=0 AND vtiger_contactaddress.mobile LIKE '%"+likemobile+"%' OR vtiger_contactaddress.phone LIKE '%"+likemobile+"%'";
... AND vtiger_contactaddress.mobile LIKE '%" + likemobile + "%' OR vtiger_contactaddress.phone LIKE %" + likemobile + "%";
try this..
var likemobile = mobile;
var query = "SELECT vtiger_contactaddress.contactaddressid as 'leadid',
vtiger_contactaddress.mobile,
vtiger_contactaddress.phone
FROM `vtiger_contactaddress`
INNER JOIN `vtiger_crmentity`
ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid AND
vtiger_crmentity.deleted=0 AND
vtiger_contactaddress.mobile LIKE '% "+likemobile+"%' OR
vtiger_contactaddress.phone LIKE '%"+likemobile +"%'";

Undefined method 'join' during mysql action (ruby/sinatra)

Undefined method 'join' during mysql action (ruby/sinatra)
Code:
rs = con.query('select * from userlog')
#logentry = ""
rs.each_hash { |h|
#logentry = #logentry + "ID: " + h['Id'] + "User: " + h['user'] + " - Time: " + h['datetime'] + " - Description: " + h['description'] + "<br>"
}
Error:
undefined method `join' for #<String:0x007f70585b68f8>
when I add ".to_s" to the "h[Id]" then I get blank results for the ID but the rest is shown.
It sounds like your 'userlog' table column name for the identifier is not 'Id', maybe 'id'. Otherwise it would have been selected normally.
I had similar problem. The reason was that table name was incorrect in database, and for some reason MySQL error messages were incorrect. Check all database, table and variable names.

DateTime is not formatted properly / Time is being Truncated

I need help because I cannot understand what I'm doing wrong here.
Initial setup:
MS Access database (.mdb).
MS Office 2010 installed.
MS SQL Server 2008
I built the routine to sync records from MS SQL Server 2008 to MS Access database. Tables are identical when it comes to table layout and number of fields
The part of the routine there is an INSERT SQL statement
and part of SQL statement this code
//Query to execute
cmdToExecute.CommandText = "INSERT INTO " + tableName +
"(EquipmentID, TimeInspected) VALUES(" +
"'" + this._strEquipmentId.ToString() + "'," +
"'" + this._dtTimeInspected.Value.ToString("yyyy-MM-dd hh:mm:ss tt") + "'";
_stTimeInspected is declared as sqlDateTime.
For some reason I cannot get Date and Time together in MS Access database table.
When I use the format like this._dtTimeInspected.Value.ToString("yyyy-MM-dd") I can get date, or
this._dtTimeInspected.Value.ToString("hh:mm:ss tt") I can get Time
but for some reason time is being truncated when I use this: _dtTimeInspected.Value.ToString("yyyy-MM-dd hh:mm:ss tt")
I even try to use parametrized query
PARAMETERS [#EquipmentID] Text ( 255 ), [#TimeInspected] DateTime;
INSERT INTO VisualInspectionHistory ( EquipmentID, , DateInspected, TimeInspected, RecordIsUpdated, DateSync, TimeSync )
SELECT [#EquipmentID] AS Expr1, [#TimeInspected] AS Expr2
/// <summary>
/// Purpose: Insert new record into database table
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override bool Insert()
{
OleDbCommand cmdToExecute = new OleDbCommand();
cmdToExecute.CommandText = "VisualInspection_Insert";
cmdToExecute.CommandType = CommandType.StoredProcedure;
cmdToExecute.Connection = conMainConnection;
try
{
cmdToExecute.Parameters.Add(new OleDbParameter("#EquipmentID", (OleDbType)OleDbType.VarChar, 25)).Value = _strEquipmentID.ToString();
cmdToExecute.Parameters.Add(new OleDbParameter("#TimeInspected", (OleDbType)OleDbType.Date)).Value = (DateTime)(_dtTimeInspected);
if (bMainConnectionIsCreatedLocal)
{
//Open connction
conMainConnection.Open();
}
else
{
if (cpMainConnectionProvider.IsTransactionPending)
{
cmdToExecute.Transaction = cpMainConnectionProvider.CurrentTransaction;
}
}
//Execute query
iRowsAffected = cmdToExecute.ExecuteNonQuery();
return true;
}
catch (OleDbException ex)
{
//Some error occured. Bubble it to caller and encapsulate Exception object
throw ex;
}
catch (Exception ex)
{
//Some error occured. Bubble it to caller and encapsulate Exception object
throw ex;
}
finally
{
if (bMainConnectionIsCreatedLocal == true)
{
//Close connection
conMainConnection.Close();
}
cmdToExecute.Dispose();
}
}
Any help would be greatly appreciated.
I found the solution.
To insert Date and time
//Query to execute
cmdToExecute.CommandText = "INSERT INTO " + tableName +
"(EquipmentID, TimeInspected) VALUES(" +
"'" + this._strEquipmentId.ToString() + "'," +
"#" + this._dtTimeInspected.Value.ToString("yyyy/MM/dd hh:mm:ss tt") + "#";
even without parametrized procedures
To insert time
`//Query to execute
cmdToExecute.CommandText = "INSERT INTO " + tableName +
"(EquipmentID, TimeInspected) VALUES(" +
"'" + this._strEquipmentId.ToString() + "'," +
"#" + this._dtTimeInspected.Value.ToString("hh:mm:ss tt") + "#";`
Thank you for your help

How to delete multiple rows (using named parameters) in Adobe AIR

I am trying to delete multiple rows in the sqlite table in my Adobe AIR app (runtime 2.5).
Here is the statement, using the "IN" operator:
"DELETE FROM mylist WHERE tdId IN (tdId1, tdId2, tdId3, ...)";
Where tdId1, tdId2, etc. will be determined at runtime based on which row(s) the user chooses to delete. The user can delete arbitrary number of rows.
I've tried something like:
//delete statement text
"DELETE FROM mylist WHERE tdId IN :tdId";
//delete statement parameters: take 1.
//Got "argument error: near ':tdId': syntax error"
deleteStmt.parameters[":tdId"] = "(26, 32)";
//delete statement parameters: take 2.
//Also got "argument error: near ':tdId': syntax error"
var arr:Array = [26, 32];
deleteStmt.parameters[":tdId"] = arr;
How I go about deleting multiple rows?
[Edit] So it looks like the aforementioned cached statement with parameter [":tdId"] doesn't work when deleting multiple rows. When attempting to execute the delete statement multiple times in asynchronous mode, after the very first row in the queue is deleted, Flash throws the following error:
"Error #3110: Operation cannot be
performed while SQLStatement.executing
is true."
It would seem too much of trouble to chain these deletes with a callback. So I guess I am using my last resort: building the sql at runtime. Conclusion: Cached statements can't be used in these kind of situations...
The problem occurs when you insert the parameter "(26,32)". As the parameter is not purely a substitution of value, it represents a variable to SQL, NOT A STRING. Hence you statement effectively became (or roughly) in your first take...
"DELETE FROM mylist WHERE tdId IN '(26,32)'"
Hence your error, due to the syntax... In your second take it gets worse...
"DELETE FROM mylist WHERE tdId IN *Array(26,32)*"
As the variable does not convert to a string value, this does not actually happen. But what happens is that when the interprater (SQL) tries to understand the code after the 'IN' text, it gets an ARRAY object, which it has completely no idea on what to do... Its not even a valid SQL type....
Solution? [I yet to fully test it, so please do]
var toDel:Array = [26,32]
//delete statement text
var baseStr:String = "DELETE FROM mylist WHERE tdId IN (";
var midStr:String = '';
//delete statement parameters: Processing parameter
for( var i = 0; i < toDel.length; i++ ) {
deleteStmt.parameters[i] = toDel[i];
if(midStr.length > 0) { midStr += ' , '; }
midStr += '?';
}
deleteStmt.text = baseStr + midStr + ' )';
//Then execute
So what happens in this case is that u effectively execute...
"DELETE FROM mylist WHERE tdId IN ( :val1 , :val2 )"
In this way you still maintain the safe (good practice) use of parameters, without converting everything to a string.
EDIT: if you dun understand the use of parameter / '?' refer to :
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/data/SQLStatement.html#parameters
If the IN clause does not allow parameters, you can try old-school SQL style: append multiple
" OR (tdId = :param" + paramCounter.toString() + ")"
to the SQL string