Sqlite ExecuteScalar throwing NullReferenceExcpetion - c#

I have a custom written DB provider. When I run my tests, they're breaking on the ExecuteScalar command with a NullReferenceException. What might I be missing here? I've read that some people have a MultiThreading issue, but I don't "think" that's what I'm running into.
Here's my GetOpenConnection method
public SqliteConnection GetOpenConnection()
{
var connection = new SqliteConnection(_connectionString);
if (connection == null) throw new Exception("Could not create a database connection.");
connection.Open();
return connection;
}
And the ExecuteScalar method
public TKey ExecuteScalar<TKey> ( string commandText, IDictionary<string, object> parameters )
{
using ( var connection = _connectionProvider.GetOpenConnection() )
{
using ( var command = connection.CreateCommand() )
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
foreach ( var parameter in parameters )
{
command.Parameters.Add( new SqliteParameter( parameter.Key, parameter.Value ?? DBNull.Value ) );
}
// BREAKING HERE
return ( TKey )command.ExecuteScalar();
}
}
}
And this is the method that's calling the ExecuteScalar
private const string CheckTableExists = "SELECT name FROM sqlite_master WHERE type='table' AND name='{0}'";
public bool CheckIfTableExists ( string tableName )
{
var exists = ExecuteScalar<int>( string.Format( CheckTableExists, tableName ) ) == 1;
return exists;
}
I put a break point on it, and try to step into it.. .and the code just breaks and throws the exception... I can't track it down

ExecuteScalar returns null if no records were returned by the query. This seems to resolve the NullReferenceException.
public TKey ExecuteScalar<TKey> ( string commandText, IDictionary<string, object> parameters )
{
using ( var connection = _connectionProvider.GetOpenConnection() )
{
using ( var command = connection.CreateCommand() )
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
foreach ( var parameter in parameters )
{
command.Parameters.Add( new SqliteParameter( parameter.Key, parameter.Value ?? DBNull.Value ) );
}
if (typeof (TKey) != typeof (int))
{
return (TKey) command.ExecuteScalar();
}
var executeScalar = command.ExecuteScalar();
var item = executeScalar == null ? 0 : 1;
return (TKey)(object)item;
}
}
}

Related

Call Oracle table of object in procedure from .net core [duplicate]

I have a SQL Server 2005 database. In a few procedures I have table parameters that I pass to a stored proc as an nvarchar (separated by commas) and internally divide into single values. I add it to the SQL command parameters list like this:
cmd.Parameters.Add("#Logins", SqlDbType.NVarchar).Value = "jim18,jenny1975,cosmo";
I have to migrate the database to SQL Server 2008. I know that there are table value parameters, and I know how to use them in stored procedures. But I don't know how to pass one to the parameters list in an SQL command.
Does anyone know correct syntax of the Parameters.Add procedure? Or is there another way to pass this parameter?
DataTable, DbDataReader, or IEnumerable<SqlDataRecord> objects can be used to populate a table-valued parameter per the MSDN article Table-Valued Parameters in SQL Server 2008 (ADO.NET).
The following example illustrates using either a DataTable or an IEnumerable<SqlDataRecord>:
SQL Code:
CREATE TABLE dbo.PageView
(
PageViewID BIGINT NOT NULL CONSTRAINT pkPageView PRIMARY KEY CLUSTERED,
PageViewCount BIGINT NOT NULL
);
CREATE TYPE dbo.PageViewTableType AS TABLE
(
PageViewID BIGINT NOT NULL
);
CREATE PROCEDURE dbo.procMergePageView
#Display dbo.PageViewTableType READONLY
AS
BEGIN
MERGE INTO dbo.PageView AS T
USING #Display AS S
ON T.PageViewID = S.PageViewID
WHEN MATCHED THEN UPDATE SET T.PageViewCount = T.PageViewCount + 1
WHEN NOT MATCHED THEN INSERT VALUES(S.PageViewID, 1);
END
C# Code:
private static void ExecuteProcedure(bool useDataTable,
string connectionString,
IEnumerable<long> ids)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "dbo.procMergePageView";
command.CommandType = CommandType.StoredProcedure;
SqlParameter parameter;
if (useDataTable) {
parameter = command.Parameters
.AddWithValue("#Display", CreateDataTable(ids));
}
else
{
parameter = command.Parameters
.AddWithValue("#Display", CreateSqlDataRecords(ids));
}
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "dbo.PageViewTableType";
command.ExecuteNonQuery();
}
}
}
private static DataTable CreateDataTable(IEnumerable<long> ids)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(long));
foreach (long id in ids)
{
table.Rows.Add(id);
}
return table;
}
private static IEnumerable<SqlDataRecord> CreateSqlDataRecords(IEnumerable<long> ids)
{
SqlMetaData[] metaData = new SqlMetaData[1];
metaData[0] = new SqlMetaData("ID", SqlDbType.BigInt);
SqlDataRecord record = new SqlDataRecord(metaData);
foreach (long id in ids)
{
record.SetInt64(0, id);
yield return record;
}
}
Further to Ryan's answer you will also need to set the DataColumn's Ordinal property if you are dealing with a table-valued parameter with multiple columns whose ordinals are not in alphabetical order.
As an example, if you have the following table value that is used as a parameter in SQL:
CREATE TYPE NodeFilter AS TABLE (
ID int not null
Code nvarchar(10) not null,
);
You would need to order your columns as such in C#:
table.Columns["ID"].SetOrdinal(0);
// this also bumps Code to ordinal of 1
// if you have more than 2 cols then you would need to set more ordinals
If you fail to do this you will get a parse error, failed to convert nvarchar to int.
Generic
public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
{
var tbl = new DataTable();
tbl.Columns.Add("Id", typeof(T));
foreach (var item in list)
{
tbl.Rows.Add(selector.Invoke(item));
}
return tbl;
}
The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)
Create this extension method...
public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
if(paramCollection != null)
{
var p = paramCollection.Add(parameterName, SqlDbType.Structured);
p.TypeName = "dbo.tvp_Int";
DataTable _dt = new DataTable() {Columns = {"Value"}};
data.ForEach(value => _dt.Rows.Add(value));
p.Value = _dt;
}
}
Now you can add a table valued parameter in one line anywhere simply by doing this:
cmd.Parameters.AddWithValueFor_Tvp_Int("#IDValues", listOfIds);
Use this code to create suitable parameter from your type:
private SqlParameter GenerateTypedParameter(string name, object typedParameter)
{
DataTable dt = new DataTable();
var properties = typedParameter.GetType().GetProperties().ToList();
properties.ForEach(p =>
{
dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
});
var row = dt.NewRow();
properties.ForEach(p => { row[p.Name] = (p.GetValue(typedParameter) ?? DBNull.Value); });
dt.Rows.Add(row);
return new SqlParameter
{
Direction = ParameterDirection.Input,
ParameterName = name,
Value = dt,
SqlDbType = SqlDbType.Structured
};
}
If you have a table-valued function with parameters, for example of this type:
CREATE FUNCTION [dbo].[MyFunc](#PRM1 int, #PRM2 int)
RETURNS TABLE
AS
RETURN
(
SELECT * FROM MyTable t
where t.column1 = #PRM1
and t.column2 = #PRM2
)
And you call it this way:
select * from MyFunc(1,1).
Then you can call it from C# like this:
public async Task<ActionResult> MethodAsync(string connectionString, int? prm1, int? prm2)
{
List<MyModel> lst = new List<MyModel>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = $"select * from MyFunc({prm1},{prm2})";
using (var reader = await command.ExecuteReaderAsync())
{
if (reader.HasRows)
{
while (await reader.ReadAsync())
{
MyModel myModel = new MyModel();
myModel.Column1 = int.Parse(reader["column1"].ToString());
myModel.Column2 = int.Parse(reader["column2"].ToString());
lst.Add(myModel);
}
}
}
}
}
View(lst);
}

invalid attempt to call read when READER IS CLOSED .. error repeat at every line

I am getting this error while i am trying to retrieve data from table.,
I am getting error at every line in while(r1.read()) loop., if i remove that line then i am getting same error in next line, it continues till last line of loop..
Please help.,
void otherdata()
{
if (conn.State == ConnectionState.Closed) conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select customer.cust_name,customer.cust_id,purchase_details.purchase_id,purchase_details.pdate,purchase_details.subtotal,purchase_details.total,purchase_details.supp_bill_id from Purchase_details inner join customer on purchase_details.supplier_id=customer.cust_id where id =" + pd;
SqlDataReader r1 = cmd.ExecuteReader();
while (r1.Read())
{
cbsupplier.Text = r1["cust_name"].ToString();
txtdate.Value = Convert.ToDateTime(r1["pdate"]);
txtsubtotal.Text = r1["subtotal"].ToString();
custid.Text = r1["cust_id"].ToString();
MessageBox.Show("pochalo");
}
r1.Close();
conn.Close();
if (conn.State == ConnectionState.Closed) conn.Open();
cmd.CommandText = "select * from purchase where purchase_id =" + pd;
r1 = cmd.ExecuteReader();
while (r1.Read())
{
txtadjust.Text = r1["adjustment"].ToString();
cbtaxrate.Text = r["taxrate"].ToString();
txttax.Text = r["tax"].ToString();
}
conn.Close();
r1.Close();
}
for your exception, i'm guessing is throwing this exception at this line :
cbtaxrate.Text = r["taxrate"].ToString();
txttax.Text = r["tax"].ToString();
because r["taxrate"] is not the same reader as r1["adjustment"]. So, i'm guessing you opened a reader with a name r in the same scope, then closed it, and opened a new reader r1 and did the above code. the issue here is not about closing the reader connection, it's about following the best practices in handling instances and naming conversion. if you chose a readable naming for your variables, it will be easer for you to read and follow the code.
You need also to use using clause on disposable objects, for a better disposal handling.
Here is a helper method that would saves you the hassle:
public static class SqlConnectionHelper
{
public static IEnumerable<KeyValuePair<string , object>> GetQueryValues(this SqlConnection connection , string sql , SqlParameter[] parameters , string[] fields)
{
if(connection == null)
{
throw new ArgumentNullException(nameof(connection));
}
var mappedFields = new Dictionary<int, string>();
using(var command = new SqlCommand(sql , connection))
{
if(parameters?.Length > 0)
{
command.Parameters.AddRange(parameters);
}
if(connection.State == ConnectionState.Closed)
connection.Open();
using(var reader = command.ExecuteReader())
{
if(reader.HasRows)
yield break;
if(fields?.Length > 0)
{
for(int x = 0; x < reader.FieldCount; x++)
{
var columnName = reader.GetName(x);
if(Array.Exists(fields , i => i.Equals(columnName , StringComparison.OrdinalIgnoreCase)))
{
mappedFields.Add(x , columnName);
}
}
while(reader.Read())
{
foreach(var field in mappedFields)
{
yield return new KeyValuePair<string , object>(field.Value , reader.GetValue(field.Key));
}
}
}
else
{
while(reader.Read())
{
for(int x = 0; x < reader.FieldCount; x++)
{
yield return new KeyValuePair<string , object>(reader.GetName(x) , reader.GetValue(x));
}
}
}
}
}
}
public static Dictionary<string , object> GetQueryUniqueValues(this SqlConnection connection , string sql , SqlParameter[] parameters , string[] fields)
{
return GetQueryValues(connection , sql , parameters , fields)
.GroupBy(x => x.Key)
.Select(x => new
{
Name = x.Key ,
Value = x.FirstOrDefault(s => s.Key == x.Key).Value
})
.ToDictionary(x => x.Name , x => x.Value);
}
}
with the reader helper, you can provide fields to get selected columns values, or you can just pass null to it and it will read all columns that have been provided under the SELECT statement.
reusing this to your current code would be like :
using(var connection = new SqlConnection(connectionString))
{
const string purchaseDetailsSql = "SELECT c.cust_name, c.cust_id, p.purchase_id, p.pdate, p.subtotal, p.total, p.supp_bill_id FROM Purchase_details p INNER JOIN customer c ON p.supplier_id = c.cust_id WHERE id = #id ;";
const string purchasesSql = "SELECT adjustment, taxrate, tax FROM purchase WHERE purchase_id = #id ;";
var parameters = new[]
{
new SqlParameter("#id", pd)
{
SqlDbType = SqlDbType.Int
}
};
var fields = new[] { "cust_name", "pdate" , "subtotal", "cust_id" };
// here would select the columns from the provided fields array.
var purchaseDetails = connection.GetQueryUniqueValues(purchaseDetailsSql , parameters, new[] { "cust_name", "pdate" , "subtotal", "cust_id" });
// here would select the columns from the query.
var purchases = connection.GetQueryUniqueValues(purchasesSql, parameters, null);
cbsupplier.Text = purchaseDetails["cust_name"]?.ToString();
txtdate.Value = Convert.ToDateTime(purchaseDetails["pdate"]);
txtsubtotal.Text = purchaseDetails["subtotal"]?.ToString();
custid.Text = purchaseDetails["cust_id"]?.ToString();
MessageBox.Show("pochalo");
txtadjust.Text = purchases["adjustment"]?.ToString();
cbtaxrate.Text = purchases["taxrate"]?.ToString();
txttax.Text = purchases["tax"]?.ToString();
}

ExecuteScalar not returning right values C#

Let me start by posting my code first:
ExecuteScalar method:
public T ExecuteScalar<T>(string sql, CommandType commandType, List<NpgsqlParameter> parameters)
{
using (NpgsqlConnection conn = Konekcija_na_server.Spajanje("spoji"))
{
return Execute<T>(sql, commandType, c =>
{
var returnValue = c.ExecuteScalar();
return (returnValue != null && returnValue != DBNull.Value && returnValue is T)
? (T)returnValue
: default(T);
}, parameters);
}
}
Execute method:
T Execute<T>(string sql, CommandType commandType, Func<NpgsqlCommand, T> function, List<NpgsqlParameter> parameters)
{
using (NpgsqlConnection conn = Konekcija_na_server.Spajanje("spoji"))
{
using (var cmd = new NpgsqlCommand(sql, conn))
{
cmd.CommandType = commandType;
if (parameters.Count > 0 )
{
foreach (var parameter in parameters)
{
cmd.Parameters.AddWithValue(parameter.ParameterName,parameter.Value);
}
}
return function(cmd);
}
}
}
Call of ExecuteScalar method:
komanda = "begin;select count(*) from radni_sati where ime=#ime and prezime=#prezime" +
" and (dolazak is not null and odlazak is not null and sati_rada is not null) and napomena='' ;commit;";
listaParametara.Add(new NpgsqlParameter { ParameterName = "#ime", Value = ime });
listaParametara.Add(new NpgsqlParameter { ParameterName = "#prezime", Value = prezime });
var nePrazni_redovi=instanca.ExecuteScalar<int>(komanda, CommandType.Text, listaParametara);
listaParametara.Clear();
Now my problem is when I call ExecuteScalar().
For some reason my ExecuteScalar always returns 0 as result and that can't be coz I tested it as a normal query in PSQL Shell and it always returns values>0 when I call legit query that has to return normal value.
First time It enters ExecuteScalar after a call, returns a returnValue from lamba operator and for example its 16, then when it goes to Execute function, somehow it returns 0 and I dont understand why, coz main thing I need ExecuteScalar for is to return count(*) value out as an int.
can you tell us how are you calling ExecuteScalar? What type is T? Also, set breakpoint to: var returnValue = c.ExecuteScalar(); and check what type is returned after you step over that line (F10). In watch window of Visual Studio you should check Type column.

Query on int fields finds row, query on char field doesn't, c# oledb

Using C# and OleDB to connect to an Access database.
I have three almost identical query strings:
"select * from stock_head where sh_id = 19;"
"select * from stock_head where sh_lineno = 32059";
"select * from stock_head where sh_ref='#007705';";
The first and second retrieve the row and the field in each case is an integer, the last one doesn't, it's a char field and the row does exist:
ExecuteQuery - select * from stock_head where sh_lineno = 32059
ID 7705, #007705, 32059, NS, 'NO SALE', 04/02/2017 14:29:00
1 row(s) found
ExecuteQuery - select * from stock_head where sh_ref='#007705';
0 row(s) found
Is there something weird about queries on character fields via C# and OleDB? I've tried using 'like' instead of '=', and single and double quotes to delimit the value, all to no avail.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
namespace OleDbTest
{
class Program
{
static void Main( string[] args )
{
// Create Profile File object
ProcessEJFile EJP = new ProcessEJFile(
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=E:\Users\sallyw\Documents\Bar.accdb;" +
"Persist Security Info=False;");
//// Get last reference from the Stock Header file
//object retVal = EJP.ExecuteScalar(
// #"SELECT max(stock_head.[sh_ref]) FROM stock_head where sh_ref like ""[#]%"";", null);
//string maxRef = retVal.ToString();
//Console.WriteLine( "maxRef = {0}", maxRef );
// Get the actual row
string query =
// #"select * from stock_head where sh_ref = '{0}';";
//"select * from stock_head where sh_id = 19;";
"select * from stock_head where sh_lineno = 32059";
List<StockHead> shlist = EJP.GetStockHead(query, null );
if ( shlist == null )
{
Console.WriteLine( "shlist is null" );
}
else
{
foreach (StockHead sh in shlist )
{
Console.WriteLine( sh.ToString() );
}
Console.WriteLine( "{0} row(s) found", shlist.Count());
}
query =
// #"select * from stock_head where sh_ref = '{0}';";
"select * from stock_head where sh_ref='#007705';";
List<StockHead> shlist1 = EJP.GetStockHead(query, null );
if ( shlist1 == null )
{
Console.WriteLine( "shlist1 is null" );
}
else
{
foreach ( StockHead sh in shlist1 )
{
Console.WriteLine( sh.ToString() );
}
Console.WriteLine( "{0} row(s) found", shlist1.Count() );
}
Console.ReadLine();
}
}
class ProcessEJFile
{
AccessDatabase Accdb = null;
public ProcessEJFile( string connectionString )
{
Accdb = new AccessDatabase( connectionString );
}
public List<StockHead> GetStockHead( string sql, params object[] args )
{
DataTable t;
Accdb.ExecuteQuery( out t, sql, args );
if ( t != null )
{
List<StockHead> shlist = new List<StockHead>();
foreach ( DataRow r in t.Rows )
{
StockHead sh = new StockHead( r);
shlist.Add( sh );
}
return shlist;
}
else
{
return null;
}
}
// Get a single value - MAX, COUNT etc.
public Object ExecuteScalar( string sql, params object[] args )
{
return Accdb.ExecuteScalar( sql, args );
}
}
class AccessDatabase
{
public OleDbConnection conn = new OleDbConnection();
public AccessDatabase( string connection )
{
conn.ConnectionString = connection;
}
public bool OpenDatabase()
{
try
{
conn.Open();
}
catch ( Exception ex )
{
return false;
}
return true;
}
public void CloseDatabase()
{
if ( conn == null )
return;
conn.Close();
}
public void ExecuteQuery( out DataTable dataTable, string sql, params object[] args )
{
dataTable = new DataTable();
string query;
// Simplified version not validating or cleaning arguments in any way
if ( args == null )
{
query = sql;
}
else
{
query = string.Format( sql, args );
}
Console.WriteLine( "\nExecuteQuery - {0}", query );
if ( OpenDatabase() )
{
OleDbCommand command = new OleDbCommand( query, conn );
OleDbDataAdapter adapter = new OleDbDataAdapter( command );
adapter.Fill( dataTable );
}
}
public object ExecuteScalar( string sql, params object[] args )
{
Object returnValue = null;
string query = sql;
if ( OpenDatabase() )
{
OleDbCommand cmd = new OleDbCommand( query, (OleDbConnection)conn);
returnValue = cmd.ExecuteScalar();
}
return returnValue;
}
}
class StockHead
{
public int sh_id;
public string sh_ref;
public int sh_lineno = 0;
public string sh_type;
public string sh_supplier = "";
public DateTime sh_datetime;
public StockHead( DataRow row )
{
this.sh_id = (int)row[ "sh_id" ];
this.sh_ref = (string)row[ "sh_ref" ];
if ( !string.IsNullOrEmpty( row[ "sh_lineno" ].ToString() ) )
{
this.sh_lineno = (int)row[ "sh_lineno" ];
}
this.sh_type = (string)row[ "sh_type" ];
if ( !string.IsNullOrEmpty( row[ "sh_lineno" ].ToString() ) )
{
this.sh_supplier = (string)row[ "sh_supplier" ];
}
this.sh_datetime = (DateTime)row[ "sh_datetime" ];
}
public override string ToString()
{
return String.Format( "ID {0}, {1}, {2}, {3}, '{4}', {5}",
this.sh_id, this.sh_ref, this.sh_lineno, this.sh_type, this.sh_supplier, this.sh_datetime );
}
}
}`
There's nothing wrong with your query. This is failing because you try to open the connection to the database each time you perform the query by calling OpenDatabase in ExecuteQuery. The second time the OpenDatabase fails as the database is already open and the query is not executed.
You are trapping the error but doing nothing with it. The message given is...
The connection was not closed. The connection's current state is open.
This can easily be found by stepping through your code. Did you not run it in debug?
You can change it to..
public bool OpenDatabase()
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
return true;
}
If you trap an error then do something with it other than returning False

get all rows of column with datatype bit

i need to pass a parameter to stored procedure to get all rows which data type of column is Bit .
example :
select * from user where active = true // get all actived users
select * from user where active = false // get all Not actived users
what can i do when i need to get all rows . i pass the active value as a parameter from C#
You can make the active parameter optional, and do something like this:
ALTER PROCEDURE [dbo].[GetUsers](
#Active BIT = NULL
) AS
BEGIN
SELECT *
FROM user
WHERE (#Active IS NULL OR active = #Active)
END
And in the code, add an overloaded fetch method:
var users = GetUsers(true); //pass active as true
var users = GetUsers(); //dont pass active parameter, return all users
Use the ? to nullify your C# bool value:
bool? showActive = SomeCode();
Pass the potentially null showActive flag and update your SQL code with this:
select * from user where active = #showActive or #showActive is null
If the #showActive parameter passed is null, all rows will be returned.
Depends what data is in active column.
If you have true and false, which I doubt, becuase sql db doesn`t support these kind of value tyes, but you at least can have bit value type. So bit can have only 1 or 0 (one or zero).
This can also be achieved like:
WHERE user.active = ISNULL(#Active, user.active)
using this, SQL server can use an index if one is available and can be used.
I like something like this. Given a stored procedure :
create procedure dbo.SelectAccounts
#fExpired bit
as
set ansi_nulls on
set concat_null_yields_null on
select *
from dbo.Account acct
where acct.Expired = #fExpired = coalesce( #fExpired , acct.Expired )
-- a more verbose alternative test
-- ( acct.Expired = #fExpired
-- OR ( acct.Expired is null
-- and #fExpired is not null
-- )
-- )
return 0
go
I generate a class that looks something like this:
public class dbo_SelectAccounts
{
public const string STORED_PROCEDURE_NAME = #"dbo.SelectAccounts";
private string ConnectString { get ; set ; }
public int ReturnCode { get ; private set ; }
public int TimeoutInSeconds { get ; private set ; }
public DataTable ResultSet { get ; private set ; }
public int RowCount { get { return this.ResultSet.Rows.Count ; } }
public int Exec( bool? #fExpired )
{
using ( SqlConnection conn = new SqlConnection( this.ConnectString ) )
using ( SqlCommand cmd = conn.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter(cmd) )
{
cmd.CommandText = STORED_PROCEDURE_NAME;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = this.TimeoutInSeconds ;
// 1. Format parameter to stored procedure
SqlParameter p1 = new SqlParameter( #"#fExpired" , SqlDbType.Bit ) ;
if ( #fExpired == null )
{
p1.Value = System.DBNull.Value ;
}
else
{
p1.Value = #fExpired ;
}
cmd.Parameters.Add( p1 );
// add return code parameter
SqlParameter pReturnCode = new SqlParameter();
pReturnCode.SqlDbType = System.Data.SqlDbType.Int;
pReturnCode.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add( pReturnCode );
conn.Open();
sda.Fill( this.ResultSet ) ;
conn.Close();
this.ReturnCode = (int)pReturnCode.Value;
}
return this.ReturnCode;
}
#region constructors
public dbo_SelectAccounts( string connectionString , int executionTimeoutInSeconds )
{
this.ConnectString = connectionString ;
this.TimeoutInSeconds = executionTimeoutInSeconds ;
this.ReturnCode = -1 ;
this.ResultSet = new DataTable() ;
return ;
}
public dbo_SelectAccounts( string connectionString )
: this( connectionString , 30 )
{
this.ConnectString = connectionString;
}
public dbo_SelectAccounts( SqlConnectionStringBuilder csb , int executionTimeoutInSeconds )
: this( csb.ConnectionString , executionTimeoutInSeconds )
{
return;
}
public dbo_SelectAccounts( SqlConnectionStringBuilder csb )
: this( csb.ConnectionString )
{
return;
}
#endregion constructors
}
Usage is simple:
dbo_SelectAccount sp = new dbo_SelectAccounts( myConnectString ) ;
int rc = sp.Exec( null ) ;

Categories

Resources