linq to sql error when trying to insert - linq-to-sql

Im trying to do an simple insert but am stuck with an error...
Error 10 The type arguments for method 'System.Data.Linq.Table<RequestSystem.User>.InsertAllOnSubmit<TSubEntity>(System.Collections.Generic.IEnumerable<TSubEntity>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
My code is
`UserModel User = new UserModel();
User.MudID = a[1];
User.Name = Session["username"].ToString();
User.Email = Session["email"].ToString();`
DataClasses1DataContext dt = new DataClasses1DataContext();
dt.Users.InsertAllOnSubmit(User);
dt.SubmitChanges();

Use the following instead:
dt.Users.InsertOnSubmit(User);
That will insert a single instance of your object. Using InsertAllOnSubmit expects a collection of objects

Related

Can I declare type of parameters for sql command? I cannot insert a boolean value, it is being considered a string

I am trying to insert into MySQL DB using Powershell, the input data is from a REST API call. I am using Prepare Statement approach to optimize the inserts, I am having issues while inserting values into a column (let my_col_bool ) which is of type Boolean (i.e tinyint(1)).
The input data received from REST API would assign values to $myVar1,$myVar3,$myVar3. The values assigned to $myVar3 would be "true / false", as I am adding these values to command parameter and Executing the query, may be it is considering these values as String instead of Boolean as I am having an Error.
Approach 1:
$oMYSQLCommand.CommandText = "INSERT INTO myTable VALUES(#my_col_string,#my_col_int,#my_col_bool)"
cmd.Prepare()
$oMYSQLCommand.Parameters.AddWithValue("#my_col_string", "")
$oMYSQLCommand.Parameters.AddWithValue("#my_col_int", "")
$oMYSQLCommand.Parameters.AddWithValue("#my_col_bool", "")
$oMYSQLCommand.Parameters("#my_col_string").Value = $myVar1
$oMYSQLCommand.Parameters("#my_col_int").Value = $myVar2
$oMYSQLCommand.Parameters("#my_col_bool").Value = $myVar3
$oMYSQLCommand.ExecuteNonQuery() /*Error: Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect integer value: 'false' for column 'my_col_bool' at row 1" */
Approach 2:
$oMYSQLCommand.Parameters.Add("#my_col_bool",[System.Data]::$SqlDbType.TinyInt) /*Error: Unable to find type [System.Data] */
Approach 3:
$oMYSQLCommand.Parameters.Add("#my_col_bool",$SqlDbType.TinyInt) /*Error: Cannot find an overload for "Add" and the argument count: "2". */
Approach 4:
$param_var = New-Object MySql.Data.MySqlClient.MySqlParameter("#my_col_bool",$SqlDbType.TinyInt)
$oMYSQLCommand.Parameters.Add($param_var) | Out-Null
$oMYSQLCommand.ExecuteNonQuery()/*Error: Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect integer value: 'false' for column 'my_col_bool' at row 1" */
Every .Net driver tries to have exact same interface as MS SQL Connector has.
MS SQL Example:
$sqlCmd = [System.Data.SqlClient.SqlCommand]::new()
[void]$sqlCmd.Parameters.AddWithValue('#param1', [System.Data.SqlTypes.SqlInt16]::new(22))
[void]$sqlCmd.Parameters.Add('#param2', [System.Data.SqlTypes.SqlInt16])
$sqlCmd.Parameters['#param2'].Value = [System.Data.SqlTypes.SqlInt16]::new(22)
Reference: System.Data.SqlTypes
So usually, the methods are same, you just have to use different namespace inside [].
Note that some .Net providers use SQL type system, and some use own type system, which is usually at [VendorName.something] namespace.
For example, MySQL seems to use [MySql.Data.MySqlClient.MySqlDbType]::%typeName% namespace,
Here is update on my approach 3, to make it work $myVar1 should be bool variable
$oMYSQLCommand.Parameters.Add("#my_col_bool",$SqlDbType.TinyInt)
[bool]$myVar3_bool=[boolean]::parse($myVar1)
$oMYSQLCommand.Parameters("#my_col_bool").Value = $myVar3_bool

How to pass a local exception object to a class?

I want to pass an error local object in a class method which will display a detail error to the user.
This is the current code:
CATCH cx_root INTO lcx_general_error.
DATA(lv_longtext) = lcx_general_error->get_longtext( ).
lcx_general_error->get_source_position(
IMPORTING
program_name = lv_program_name
include_name = lv_include_name
source_line = lv_program_line
).
DATA(lv_program_include) = |{ lv_program_name }/ { lv_include_name }|.
DATA(lv_length_message) = strlen( lv_longtext ).
DATA(lv_error_message1) = lv_longtext(50).
IF lv_length_message > 50.
DATA(lv_remaining) = lv_length_message - 50.
DATA(lv_error_message2) = lv_longtext+50(lv_remaining).
ENDIF.
MESSAGE e001 WITH lv_error_message1 lv_error_message2
lv_program_include
lv_program_line.
Instead, I want to create a class method and pass any local object that refers to any error and display the error detail message:
CATCH cx_root INTO lcx_general_error.
lo_fi_uploads->display_error( lcx_general_error ).
How to create and use this parameter in the local class?
Exceptions are regular classes with regular object instances, so declare them like any other object parameter:
METHODS display_error
IMPORTING
exception TYPE REF TO cx_root.
In the method’s implementation you can then paste the code you already have:
METHOD display_error.
DATA(lv_longtext) = exception->get_longtext( ).
exception->get_source_position(
IMPORTING
program_name = DATA(lv_program_name)
include_name = DATA(lv_include_name)
source_line = DATA(lv_program_line)
).
DATA(lv_program_include) = |{ lv_program_name }/ { lv_include_name }|.
DATA(lv_length_message) = strlen( lv_longtext ).
DATA(lv_error_message1) = lv_longtext(50).
IF lv_length_message > 50.
DATA(lv_remaining) = lv_length_message - 50.
DATA(lv_error_message2) = lv_longtext+50(lv_remaining).
ENDIF.
MESSAGE e001 WITH lv_error_message1 lv_error_message2
lv_program_include
lv_program_line.
ENDMETHOD.
People often fear that working with exceptions might accidentally trigger them. That won’t happen. As long as you do not invoke the RAISE statement, exceptions are really quite ordinary objects. You can even instantiate them with NEW without triggering them.

SimpleJdbcCall for MySql Function yields "Can't set IN parameter for return value of stored function call"

Using the example from the Spring docs, I'm trying to return a value from a mySQL function. I keep getting the error Can't set IN parameter for return value of stored function call;.
I created a mySQL function that works fine (ran in MySQL Workbench). I've written a SimpleJdbcCall statement, set up the parameters as per Spring docs example but consistently get this error. If I turn the function into a procedure, the code works, I just have to retrieve the return value from the result set.
I used https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch13s05.html, section 13.5.8 as reference.
CREATE FUNCTION `ScenarioRegistration`(
environment VARCHAR(45),
username VARCHAR(15),
scenario_name VARCHAR(45)) RETURNS int(11)
A couple of SELECT statements followed by an INSERT then
RETURN scenario_id; // The inserted id
Java code:
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(getJdbcTemplate())
.withFunctionName("ScenarioRegistration")
.withoutProcedureColumnMetaDataAccess();
simpleJdbcCall.addDeclaredParameter(new SqlParameter("environment"
,Types.VARCHAR));
simpleJdbcCall.addDeclaredParameter(new SqlParameter("username"
,Types.VARCHAR));
simpleJdbcCall.addDeclaredParameter(new SqlParameter("scenario_name"
,Types.VARCHAR));
SqlParameterSource parameters = new MapSqlParameterSource()
.addValue("environment", environment)
.addValue("username", username)
.addValue("scenario_name", scenario);
simpleJdbcCall.setReturnValueRequired(true);
Integer scenario_id = simpleJdbcCall.executeFunction(
Integer.class, parameters);
All I want the routine to do is give me back the id of the newly inserted scenario.
What I get is:
SQL [{? = call scenarioregistration(?, ?)}]; Can't set IN parameter for return value of stored function call.
I find it interesting that it's taken my THREE input values and changed them to an output and TWO input values.
Anyone enlighten me as to the problem and how to fix it?
Thanks,
Steven.
I would refer to the latest docs here for your answer. It appears Spring is trying to infer the output because you didn't explicity specify one.
Per the docs above there are two valid approaches on calling the desired function with the SimpleJdbcCall:
Inferred Parameters
Because you've specified withoutProcedureColumnMetaDataAccess, Spring isn't going to look and see what the ins/outs are to your function. If you want it easy, just don't specify that and you should be able to do:
SqlParameterSource parameters = new MapSqlParameterSource()
.addValue("environment", environment)
.addValue("username", username)
.addValue("scenario_name", scenario);
Integer scenarioId = new SimpleJdbcCall(getJdbcTemplate())
.withFunctionName("ScenarioRegistration")
.executeFunction(Integer.class, parameters);
Explicit Parameters
If you want to keep withoutProcedureColumnMetaDataAccess turned off for whatever reason, you can do:
Integer scenarioId = new SimpleJdbcCall(getJdbcTemplate)
.withFunctionName("ScenarioRegistration")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("environment", "username", "scenario_name")
.declareParameters(
new SqlOutParameter("scenario_id", Types.NUMERIC),
new SqlParameter("environment", Types.VARCHAR),
new SqlParameter("username", Types.VARCHAR),
new SqlParameter("scenario_name", Types.VARCHAR)
).executeFunction(Integer.class, parameters);
Note: It appears that order is critical in this example. The output parameter should be declared first, and the subsequent named IN parameters come last. That is, the order of the parameters ? are ordinal in [{? = call scenarioregistration(?, ?, ?)}])
Alternative NamedParameterJdbcTemplate Solution
Another way to invoke your function is via an actual JDBC call. This could hypothetically save you the grief of using the fine tuning of the SimpleJdbcCall.
Integer scenarioId = namedParameterJdbcTemplate.queryForObject(
"SELECT ScenarioRegistration(:environment, :username, :scenario_name)",
parameters,
Integer.class);

Insert query failing when using a parameter in the associated select statement in SQL Server CE

INSERT INTO voucher (voucher_no, account, party_name, rece_amt, particulars, voucher_date, voucher_type, cuid, cdt)
SELECT voucher_rec_no, #account, #party_name, #rece_amt, #particulars, #voucher_date, #voucher_type, #cuid, #cdt
FROM auto_number
WHERE (auto_no = 1)
Error:
A parameter is not allowed in this location. Ensure that the '#' sign is in a valid location or that parameters are valid at all in this SQL statement.
I've just stumbled upon this whilst trying to fix the same issue. I know it's late but, assuming that you're getting this error when attempting to execute the query via .net, ensure that you are setting the SqlCeParameter.DbType - if this is not specified, you get the exception you listed above.
Example (assume cmd is a SqlCeCommand - all the stuff is in the System.Data.SqlServerCe namespace):
SqlCeParameter param = new SqlCeParameter();
param.ParameterName = "#SomeParameterName";
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String; // this is the important bit to avoid the exception
param.Value = kvp.Value;
cmd.Parameters.Add(param);
Obviously, you'd want to set the DB type to match the type of your parameter.

Single table inheritance and changing type won't save

I have a STI model where the subclasses of each use different validations. The Rails defaults will run the original type's validations at runtime, so I am trying to use "becomes" to force the validations of the new type.
My code looks like this:
payment_processor = PaymentProcessor.where(:account_id => self.id).first_or_initialize
new_gateway = "PaymentProcessors::#{gateway_type.classify}".constantize
payment_processor = payment_processor.becomes(new_gateway)
payment_processor.type = new_gateway
payment_processor.assign_attributes(attributes)
payment_processor.save!
However, it won't save because the MySQl generated during save is looking for the new type. So, for example, if my initial gateway_type is "AuthorizeNet" and I'm changing to "PayPal", the MySQL is:
UPDATE `payment_processors` SET `type` = 'PaymentProcessors::PayPal', `updated_at` = '2015-11-07 11:53:53' WHERE `payment_processors`.`type` IN ('PaymentProcessors::PayPal') AND `payment_processors`.`id` = 232
But it should be looking for the original type, Auth.net like this:
UPDATE `payment_processors` SET `type` = 'PaymentProcessors::PayPal', `updated_at` = '2015-11-07 11:53:53' WHERE `payment_processors`.`type` IN ('PaymentProcessors::AuthorizeNet') AND `payment_processors`.`id` = 232
Any ideas on how to skip the "where clause" to just update by the payment_processor ID?
I learned that STI fails on validation when attempting a type change. (Read more http://blog.arkency.com/2013/07/sti). So, I solved the problem by always creating a new payment_processor but restoring the old if validation fails. It's inelegant, but it works.
Copy the original payment_processor then delete it:
original = self.payment_processor.destroy
self.payment_processor.destroy
Instead of passing the new type, we delete it from the params, but use the new_gateway_type to create the new gateway.
new_gateway_type = params[:payment_processor][:gateway_type]
params[:payment_processor].delete(:gateway_type)
For example, if the new gateway is 'Paypal', we'll constantize the new_gateway_type to create a new object, then update the params:
payment_processor = "PaymentProcessors::#{new_gateway_type}".constantize.new(:account_id => self.id)
payment_processor.update_attributes(params[:payment_processor)
Finally, we save the new gateway. If the validation fails for this new_gateway, we restore the old by constantizing the object model name, and passing in the new attributes except for type and id:
begin
payment_processor.save!
rescue ActiveRecord::RecordInvalid => invalid
original.type.constantize.new(original.attributes.except("id", "type")).save
end