I have a simple insert statement to a table in an SQLite database on MonoDroid.
When inserting to the database, it says
SQLite error Insufficient parameters supplied to the command at Mono.Data.Sqlite.SqliteStatement.BindParameter
I think there is either a bug, or the error message is misleading. Because I only have 5 parameters and I am providing 5 parameters, so I cannot see how this be right.
My code is below, and any help would be greatly appreciated.
try
{
using (var connection = new SqliteConnection(ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandTimeout = 0;
command.CommandText = "INSERT INTO [User] (UserPK ,Name ,Password ,Category ,ContactFK) VALUES ( #UserPK , #Name , #Password , #Category , #ContactFK)";
command.Parameters.Add(new SqliteParameter("#Name", "Has"));
command.Parameters.Add(new SqliteParameter("#Password", "Has"));
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
command.Parameters.Add(new SqliteParameter("#ContactFK", DBNull.Value));
command.Parameters.Add(new SqliteParameter("#UserPK", DbType.Guid) {Value = Guid.NewGuid()});
var result = command.ExecuteNonQuery();
return = result > 0 ;
}
}
}
catch (Exception exception)
{
LogError(exception);
}
Your spelling for #Category in INSERT statement is different from added parameter.
You have:
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
^^^^^^^^^^^
//#Category
Where it should be:
Modify your statement to:
command.Parameters.Add(new SqliteParameter("#Category", ""));
This has already been answered correctly, but I wish to add, for further information:
This specific SQLite error string can also be generated if any of the #Parameters are spelled differently in the INSERT statement vs the AddWithValue or .Add(new SqliteParameter... statements.
Related
I'm using Microsoft Access file as database. I have no problem with SELECT and INSERT queries but when I try to UPDATE, record in database does not change.
Below is the code I use to run update. There are no exceptions or errors in debug log.
cnn = new OleDbConnection(connetionString);
OleDbCommand command = new OleDbCommand("UPDATE [Wpisy] SET [wpis]=#wpis, [id_kat]=#id_kat, [tytul]=#tytul WHERE [ID]=#id_wpis" , cnn);
command.Parameters.Add(new OleDbParameter("#wpis", tresc_wpisu.Text));
command.Parameters.Add(new OleDbParameter("#id_kat", lista_kategorii.SelectedValue));
command.Parameters.Add(new OleDbParameter("#tytul", tytul_wpisu.Text));
command.Parameters.Add(new OleDbParameter("#id_wpis", Request["id"].ToString() ));
command.Connection = cnn;
try
{
if(cnn.State.ToString() != "Open")
cnn.Open();
command.ExecuteNonQuery();
cnn.Close();
}
catch (OleDbException ex)
{
Response.Clear();
Response.Write(ex);
Response.End();
}
I would go to Microsoft Access and enter the command there and see what happens. It should tell you how many rows was affected. If it says zero rows, then break your query into smaller pieces, such as:
select * where [ID]=value
And then you should be able to track down where the problem is.
I know this isn't an exact answer, but there are some quirks with working with MS Access.
Here is an example method for you with some proper exception handling for databases. For Object, create a class that represents a row fields in your table. I use Exception ex instead of the db library exception since I use DataReaders for selects.
private String connectionString = "someOleDbConnectionString";
public String UpdateObject(Object obj)
{
OleDbConnection connection = GetMyOleDbConnection(); //returns new OleDbConnection with proper connection string
String updateSql = "UPDATE [Wpisy] SET [wpis]=#wpis, [id_kat]=#id_kat, [tytul]=#tytul WHERE [ID]=#id_wpis";
OleDbCommand command = new OleDbCommand(updateSql, connection);
command.CommandType = System.Data.CommandType.Text; //this can be changed if you have stored procedures in your db.
//you may have to define the OleDbType of the parameter being defined
command.Parameters.Add(new OleDbParameter("#wpis", OleDbType.VarChar, obj.tresc_wpisu));
command.Parameters.Add(new OleDbParameter("#id_kat", OleDbType.VarChar, obj.lista_kategorii));
command.Parameters.Add(new OleDbParameter("#tytul", OleDbType.VarChar, obj.tytul_wpisu));
command.Parameters.Add(new OleDbParameter("#id_wpis", OleDbType.Integer, obj.id.ToString()));
return Execute(connection, command);
}
private OleDbConnection GetMyOleDbConnection()
{
return new OleDbConnection(connectionString);
}
private String Execute(OleDbConnection connection, OleDbCommand command)
{
try
{
connection.Open();
command.ExecuteNonQuery();
//I also know with Access databases,
//sometimes you have to close the table if it is open in MS Access
connection.Close();
return "SUCCESS";
}
catch (Exception ex)
{
connection.Close(); //important or you will have left open connections
Response.Clear();
Response.Write(ex.Message);
Response.End();
return ex.Message;
}
}
I could be wrong, but from what I remember, OleDB doesn't allow named parameters, but instead use "?" as a place-holder, and the parameters need to be added in the same sequence as they appear in the SQL statement. such as
String updateSql = "UPDATE [Wpisy] SET [wpis]=?, [id_kat]=?, [tytul]=? WHERE [ID]=?";
command.Parameters.Add(new OleDbParameter("parm_wpis", OleDbType.VarChar, obj.tresc_wpisu));
command.Parameters.Add(new OleDbParameter("parm_id_kat", OleDbType.VarChar, obj.lista_kategorii));
command.Parameters.Add(new OleDbParameter("parm_tytul", OleDbType.VarChar, obj.tytul_wpisu));
command.Parameters.Add(new OleDbParameter("parm_id_wpis", OleDbType.Integer, obj.id.ToString()));
Naming the parameters is just for clarification to know which is which. One other issue might be that you named the parameters by the same name as the column being updated, and that may have been the issue almost like a constant...
set X = X instead of now set X = parmX... there is no ambiguity the you are setting to the PARAMETER value being applied. But overall, I do think it will work via using "?" as the parameter place-holder.
I can't seem to figure out why my update statement isn't working. I have a lot of similar operations to the database, inserting, selecting, deleting and they are all working well. Except for update, it doesn't seem to work. I've tried the SQL statement in MS Access on the same database, replacing the '#parameters' with values and it worked just fine.
I tried debugging and all the data from my object is valid and correct. But when I execute the command, it returns 0 and no rows were updated. My code is bellow, keep in mind that I'm rather new to C#.
public int UpdateActiviteit(Activiteit activiteit)
{
connection.Open();
OleDbCommand command = new OleDbCommand("Update Activiteit set Naam = #naam, Beschrijving = #beschrijving, TypeActiviteitID = #typeActiviteitId, BonusPunten = #bonusPunten, Datum = #datum where id = #id", connection);
command.Parameters.Add(new OleDbParameter("#naam", activiteit.Naam));
command.Parameters.Add(new OleDbParameter("#beschrijving", activiteit.Beschrijving));
command.Parameters.Add(new OleDbParameter("#typeActiviteitId", activiteit.TypeActiviteitId));
command.Parameters.Add(new OleDbParameter("#bonusPunten", activiteit.BonusPunten));
command.Parameters.Add(new OleDbParameter("#datum", activiteit.Datum));
command.Parameters.Add(new OleDbParameter("#id", activiteit.ID));
int rowsAffected = command.ExecuteNonQuery();
connection.Close();
return rowsAffected;
}
I am trying to execute a stored procedure with this declaration:
ALTER PROCEDURE [dbo].[getByName]
#firstName varchar,
#lastName varchar
AS
...
And I am calling in C# as follows:
public List<Person> GetPersonByName(string first, string last)
{
var people = new List<Person>();
var connString = ConfigurationManager.ConnectionStrings["MyDbConnString"].ConnectionString;
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand("dbo.getByName",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#firstName", SqlDbType.VarChar, 50)).Value = first;
cmd.Parameters.Add(new SqlParameter("#lastName", SqlDbType.VarChar, 50)).Value = last;
conn.Open();
using (var reader = cmd.ExecuteReader())
{
people = ReadPeopleData(reader);
}
conn.Close();
}
}
return people;
}
But I just get back this error:
Procedure or function 'getByName' expects parameter '#firstName' which was not supplied.
Update:
ALTER PROCEDURE [dbo].[getEmployeesByName]
#firstName varchar(50),
#lastName varchar(50)
AS
...
and stating:
cmd.Parameters.Add(new SqlParameter("#firstName", SqlDbType.VarChar, 50)).Value
for both parameters, yet it continues to throw the exception.
I have seen this issue occur many, many times in two common scenarios:
The value being assigned to the parameter is null (or Nothing in VB.Net). This is the .Net null, not the DB null (DBNull.Value) and this happens most commonly with strings.
The parameter being created is associated with the wrong command object. This commonly occurs when you have multiple command objects in the same class with similar names.
Please double-check the code to ensure that the string variable is not set to null and that the parameter is being added to the correct command.
Update
Based on the full updated code that was posted, the likely issue is 1 above.
To circumvent this problem in your code, add the following at the top of the method:
if (first == null) {
first = "";
}
if (last == null) {
last = "";
}
Try this it will work:
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("#UserName",(object)userName ?? DBNull.Value),
new SqlParameter("#Password",(object)password ?? DBNull.Value)
};
If parameter is NULL than replace it with DBNull Type using ?? Operator
Please add CommandaType to SQLCommand.
e.g: scmd.CommandType = CommandType.StoredProcedure;
I have a simple insert statement to a table in an SQLite database on MonoDroid.
When inserting to the database, it says
SQLite error Insufficient parameters supplied to the command at Mono.Data.Sqlite.SqliteStatement.BindParameter
I think there is either a bug, or the error message is misleading. Because I only have 5 parameters and I am providing 5 parameters, so I cannot see how this be right.
My code is below, and any help would be greatly appreciated.
try
{
using (var connection = new SqliteConnection(ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandTimeout = 0;
command.CommandText = "INSERT INTO [User] (UserPK ,Name ,Password ,Category ,ContactFK) VALUES ( #UserPK , #Name , #Password , #Category , #ContactFK)";
command.Parameters.Add(new SqliteParameter("#Name", "Has"));
command.Parameters.Add(new SqliteParameter("#Password", "Has"));
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
command.Parameters.Add(new SqliteParameter("#ContactFK", DBNull.Value));
command.Parameters.Add(new SqliteParameter("#UserPK", DbType.Guid) {Value = Guid.NewGuid()});
var result = command.ExecuteNonQuery();
return = result > 0 ;
}
}
}
catch (Exception exception)
{
LogError(exception);
}
Your spelling for #Category in INSERT statement is different from added parameter.
You have:
command.Parameters.Add(new SqliteParameter("#Cateogry", ""));
^^^^^^^^^^^
//#Category
Where it should be:
Modify your statement to:
command.Parameters.Add(new SqliteParameter("#Category", ""));
This has already been answered correctly, but I wish to add, for further information:
This specific SQLite error string can also be generated if any of the #Parameters are spelled differently in the INSERT statement vs the AddWithValue or .Add(new SqliteParameter... statements.
I am sending ID as outparameter but its giving error
System.Data.SqlClient.SqlException: Procedure or function
'usp_ClientHistoryItem' expects parameter '#ID', which was not
supplied.
Code
using (SqlCommand cmd = new SqlCommand("dbo.usp_ClientHistoryItem", conn))
{
SqlParameter parameterID = new SqlParameter("#ID", oReservation.Id);
parameterID.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parameterID);
cmd.Parameters.Add(new SqlParameter("#PhoneNo", oReservation.ClientPhone));
cmd.Parameters.Add(new SqlParameter("#UserId", oReservation.UserID));
cmd.Parameters.Add(new SqlParameter("#Description", oReservation.Description));
cmd.Parameters.Add(new SqlParameter("#TestId", oReservation.TestId));
cmd.Parameters.Add(new SqlParameter("#StartDate", oReservation.StartDate));
cmd.ExecuteNonQuery();
returnValue = Convert.ToInt32(cmd.Parameters["#ID"].Value);
return returnValue;
}
You seem to be calling a stored procedure - yet you've never defined your SqlCommand to be a stored procedure:
using (SqlCommand cmd = new SqlCommand("dbo.usp_ClientHistoryItem", conn))
{
cmd.CommandType = CommandType.StoredProcedure; // add this line to tell ADO.NET it's a stored procedure!!
If you forget that line, then ADO.NET will try to interpret your stuff as an ad-hoc SQL statement....
this one solve my problem
may be it may helpful
cmd.CommandType = CommandType.StoredProcedure;
Your ID parameter in the stored procedure must be set as OUTPUT parameter. You are just setting it in code not in stored procedure.
Hy guys.
You have to set the property CommandType for the Command to StoredProcedure if that's the case. Otherwise it woun't detect the parameters.
One other reason this error is thrown is when the variable names don't match in your stored procedure and code because the code fails to find the parameter to which the value must be passed. Make sure they match:
Stored procedure:
create procedure getEmployee
#ID
as
Begin
select *
from emp
where id = #ID
End
Code:
SqlParameter p = new SqlParameter("#ID", id);
cmd.Parameter.Add(p);
The parameter #ID must match in both code and stored procedure
If you use dapper, you can use this construction
int id = 1;
var parameters = new DynamicParameters();
parameters.Add("#id", id, DbType.Int32, ParameterDirection.Input);
string sqlQuery = "[dbo].[SomeStoredProcedure]";
using (IDbConnection db = new SqlConnection(ConnectionString))
{
var result = await db.QueryAsync<SpResult>(sqlQuery, parameters, commandType: CommandType.StoredProcedure);
}