This question already has an answer here:
Error With SqlCommand not accepting Parameter Arguments
(1 answer)
Closed 6 months ago.
The following image is the code used to call MS=SQL stored procedure, as you can see, I am attempting to provide parameters in the request
using (SqlConnection connection = new SqlConnection(sqlAuth)) {
// Open database connectionS
connection.Open();
// Call upon stored procedure
SqlCommand cmd = new SqlCommand("InsertSystem", connection);
cmd.Parameters.Add("#ObjectID", SqlDbType.VarChar).Value = Request.Form["objectid"].ToString();
cmd.Parameters.Add("#SystemID", SqlDbType.VarChar).Value = Request.Form["systemid"].ToString();
cmd.Parameters.Add("#ItemID", SqlDbType.Int).Value = Request.Form["itemid"].ToString();
int records = cmd.ExecuteNonQuery();
// Close database connection
connection.Close();
}
message = "Record Saved<br /><br />";
The error which is returned from this is as follows:
System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Procedure or function 'InsertSystem' expects parameter '#SystemID', which was not supplied.
Source=Core .Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ServiceObjectsWebApp.Pages.ObjectInsertModel.OnPost() in C:\Users\rmcd\Desktop\ServiceObecjts\ServiceObjectsWebApp\Pages\ObjectInsert.cshtml.cs:line 46
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.VoidHandlerMethod.Execute(Object receiver, Object[] arguments)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.<InvokeHandlerMethodAsync>d__29.MoveNext()
This exception was originally thrown at this call stack:
[External Code]
ServiceObjectsWebApp.Pages.ObjectInsertModel.OnPost() in ObjectInsert.cshtml.cs
[External Code]
You're calling a stored procedure so you need to tell it that:
cmd.CommandType = CommandType.StoredProcedure;
Related
MS sql 2014 backend (on same machine) - Executereader times out (native error code: 258) # second executereader() in same connection. Why is this so?
(No big data amount involved, cmd strings involved are correct)
Note: it doesn't matter if all SELECT goes into separate connection the second always times out. It also doesn't matter if I'd use DataAdapter to catch data.... times out... see below, thanks for the ideas:
using (SqlConnection c = new SqlConnection(cString))
{
c.Open();
using (SqlCommand cmd = new SqlCommand(querystringPO, c))
{
cmd.Parameters.AddWithValue("#paramRecipe", productionOrderNo);
using (SqlDataReader rd = cmd.ExecuteReader())
{
dtRecipe = new DataTable();
dtRecipe.Load(rd);
rd.Close();
}
}
if (dtRecipe.Rows.Count > 0)
{
string querystringOpDefs = "SELECT * FROM ReferencedFieldsView_OperationDefinition WHERE RecipeID=#paramOpDef";
using (SqlCommand cmd1 = new SqlCommand(querystringOpDefs, c))
{
cmd1.Parameters.AddWithValue("#paramOpDef", dtRecipe.Rows[0].Field<int>("ID"));
using (SqlDataReader rd = cmd1.ExecuteReader())
{
dtOpDefs = new DataTable();
dtOpDefs.Load(rd);
rd.Close();
}
}
string querystringBOMItems = "SELECT * FROM ReferencedFieldsView_BomItem WHERE RecipeID=#paramBOMItem";
using (SqlCommand cmd2 = new SqlCommand(querystringBOMItems, c))
{
cmd2.Parameters.AddWithValue("#paramBOMItem", dtRecipe.Rows[0].Field<int>("ID"));
using (SqlDataReader rd = cmd2.ExecuteReader())
{
dtBOMItems = new DataTable();
dtBOMItems.Load(rd);
}
}
}
}
Ex below:
Exception: System.InvalidOperationException: Server operation encountered an exception ---> System.Data.SqlClient.SqlException: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
Fact of the matter is that using SQL 2K12 the above snippet all worked (same database same etc)
However as sb suggested instead of selecting all fields (*), when explicitly added the req'd fields it started to work.
I have a code to create database with dapper:
public static bool CreateDatabase(string connectionString, string databaseName)
{
const string DATABASE_CREATE_QUERY = "CREATE DATABASE (#databaseName)";
using (var connection = new SqlConnection(connectionString))
{
var affectedRows = connection.Execute(DATABASE_CREATE_QUERY, new { databaseName });
return affectedRows > 0 ? true : false;
}
}
CreateDatabase("Server=10.10.10.10;User ID=user;Password=password;MultipleActiveResultSets=true;", "TEST_DB");
Every time I run this method, I get an error:
Incorrect syntax near '('.
With trace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) in E:\GitHub\Dapper\Dapper\SqlMapper.cs:line 2827
at Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) in E:\GitHub\Dapper\Dapper\SqlMapper.cs:line 570
at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) in E:\GitHub\Dapper\Dapper\SqlMapper.cs:line 443
at DbCreator.DbUtils.CreateDatabase(String connectionString, String databaseName) in E:\src_projects\DbCreator\DbUtils.cs:line 48
at DbCreator.***.Run(String connectionString) in E:\src_projects\DbCreator\***.cs:line 23
If I set the query the ugly way
const string DATABASE_CREATE_QUERY = $"CREATE DATABASE {databaseName}";
and run
connection.Execute(DATABASE_CREATE_QUERY);
it all works fine.
If I don't use the brackets () in the QUERY
const string DATABASE_CREATE_QUERY = "CREATE DATABASE #databaseName";
I get an error:
Incorrect syntax near '#databaseName'
I have also tried methods ExecuteScalar, Query, but with the same result.
Any ideas why this wont work the Dapper way?
This is because sp_executesql is being used for parameterizing.This is what is being executed in the database via Dapper interpretation;
exec sp_executesql N'Create Database (#DBName)',N'#DBName nvarchar(4000)',#DBName=N'Test'
See why that wont work with sp_executesql: Table name as variable
Your best bet would be to either create a stored procedure, or use the approach of string replacement.
Because create database statement doesn't require ().
Try :
const string DATABASE_CREATE_QUERY = "CREATE DATABASE #databaseName";
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to connect to sql server but I have this error:
System.InvalidOperationException: ExecuteNonQuery requires an open and
available Connection. The connection's current state is closed. at
System.Data.SqlClient.SqlCommand.ValidateCommand(String method,
Boolean async) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
FattureServer.Form1.button4_Click(Object sender, EventArgs e)
string dbserver2 = textBox4.Text;
string dbname2 = textBox1.Text;
string dbusername2 = textBox2.Text;
string dbpassword2 = textBox3.Text;
SqlConnection conn2 = new SqlConnection("Data Source=" + dbserver + ";Initial Catalog=" + dbname + ";User ID=" + dbusername + ";Password=" + dbpassword + "");
// SqlCommand cmd2 = new SqlCommand("INSERT INTO Cliente (IdCliente,IdUtente,RagioneSociale,Titolo,Indirizzo,Stato,Provincia,Citta,Comune,Cap,Telefono,Email) VALUES(#idcliente,#username,#password, #email)", conn2);
string query2 = "INSERT INTO Cliente (Titolo,RagioneSociale) VALUES(#Titolo,#RagioneSociale)";
SqlCommand myCommand = new SqlCommand(query2, conn2);
myCommand.Parameters.AddWithValue("#Titolo", titolo);
myCommand.Parameters.AddWithValue("#RagioneSociale", ragionesociale);
myCommand.ExecuteNonQuery();
conn2.Close();
how can solve this error?
EDIT:
if i insert conn2.open() i have this error:
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Cliente'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at FattureServer.Form1.button4_Click(Object sender, EventArgs e) in C:\Users\riccardo\Desktop\FattureServer\FattureServer\Form1.cs:line 189 ClientConnectionId:02db8bd4-e91a-4b43-9ba9-e1717c9e96de Error Number:208,State:1,Class:16
you forgot to do a conn2.Open(); before executing the command.
Edit. David Brabant is correct...you should be wrapping everything in a using statement.
Edit 2. It looks like your table "Cliente" is created in the DB. Are you sure you're pointing to the right database and that the table already exists?
Invalid object name 'Cliente'
That is another question.
Perhaps, a typo. Client? Check your data objects to avoid typos.
I have a stored procedure which works fine when executed manually but when it is called on the code it return a Null Reference Exception because of a TimeOut. Here's the code:
private DataTable GetProcedure(DateTime dtStart, DateTime dtEnd) {
DataTable dt = new DataTable();
SqlDataReader reader;
string cs = //Connection String, it works everywhere, no need to put the code.
SqlConnection sqlConnection = new SqlConnection(cs);
string cmdText = "ProcedureName";
SqlCommand cmd = new SqlCommand(cmdText, sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter pFechaInicio = new SqlParameter("#dtStart", dtStart);
SqlParameter pFechaFin = new SqlParameter("#dtEnd", dtEnd);
cmd.Parameters.Add(pFechaInicio);
cmd.Parameters.Add(pFechaFin);
sqlConnection.Open();
reader = cmd.ExecuteReader(); //NULL REFERENCE EXCEPTION HERE
dt.Load(reader);
sqlConnection.Close();
return dt;
}
I made a manual call to the stored procedure with the exact same parameters and it worked fine (The stored procedure returns a 3 row / 2 column result with no NULLs whatsoever.
Even more, this error started happening 1 month ago but the program has been running for 6 months flawlesly.
EDIT: Here's some info on the SP:
SP header:
ALTER PROCEDURE [dbo].[SPName]
#dtStart datetime, #dtEnd datetime
AS
BEGIN
SET NOCOUNT ON;
select column1 as Name1, column2 as Name2
/* doesn't matter */
END
The specific result I'm getting when I execute the SP manually is:
column1 column2
1.0000000 105.426890
2.0000000 96.316330
3.0000000 82.849690
And here's the whole error code:
en System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
en System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
en System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
en System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
en System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
en System.Data.SqlClient.SqlDataReader.get_MetaData()
en System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
en System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
en System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
en System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
en System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
en System.Data.SqlClient.SqlCommand.ExecuteReader()
en BACK.OFERTAS.COBERTURAS.PRECIOS._01._00.StartJob.GetProcedure(DateTime dtStart, DateTime dtEnd) en C:\Users\Dell\Documents\BACK.OFERTAS.COBERTURAS.PRECIOS.01.00\StartJob.cs:línea 278
en BACK.OFERTAS.COBERTURAS.PRECIOS._01._00.StartJob.Start() en C:\Users\Dell\Documents\BACK.OFERTAS.COBERTURAS.PRECIOS.01.00\StartJob.cs:línea 176
Re-Reading the whole stackTrace it seems like a Timeout? How is that even possible, there SP is executed in less than 1 sec.
I've solved it changing the TimeOut time of the procedure (which was of 30 secs by default).
This happens because it isn't the same to execute a SP directly on the server than in the job.
I am trying to use structs as parameters in Dapper queries. It does not work for me. But it seems like it should work.
A failing example:
struct Simple { public int ID; }
[TestMethod]
public void StructParameter()
{
int result = Db.Query<int>("select [ID] = #ID", new Simple { ID = 123 }).First();
result.Should().Be(123);
}
A working example:
[TestMethod]
public void AnonymousParameter()
{
int result = Db.Query<int>("select [ID] = #ID", new { ID = 123 }).First();
result.Should().Be(123);
}
The error thrown in the first case:
System.Data.SqlClient.SqlException: Must declare the scalar variable "#ID".
Result StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at Dapper.SqlMapper.<QueryImpl>d__11`1.MoveNext() in d:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1553
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in d:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1443
...
I am using Dapper version 1.38.
Per suggestion by Dirk, property instead of a filed works just fine:
struct Simple {
public int ID { get; set; }
}
The problem is not caused by using structs, it's caused by using fields instead of properties.
If you'd change struct Simple into class Simple is still wouldn't work because the parameter reader creates only IL code to read properties.
Changing the ID field into a property will solve it.