Issue while retrieving data using ADO.Net - c#

from my application I am retrieving data using ADO.Net classes.
private DataSet GetData(string clientconstr,string actionparam,string userid)
{
DataSet dsData = null;
SqlParameter[] objSqlParam = new SqlParameter[2];
objSqlParam[0] = new SqlParameter("#ACTION", SqlDbType.VarChar, 50);
objSqlParam[0].Value = actionparam;
objSqlParam[1] = new SqlParameter("#USERID", SqlDbType.VarChar, 100);
objSqlParam[1].Value = userid;
dbc = new dbClass(clientconstr);
dsData = dbc.ExecuteNonQuery("SPLINV", "SP", objSqlParam);
}
class dbClass
{
SqlCommand cmd = null;
SqlConnection con = null;
SqlDataAdapter da = null;
string connectionstring = "";
public dbClass(string conStr)
{
connectionstring = conStr;
}
public DataSet ExecuteNonQuery(string query, string querytype, SqlParameter[] objArrSqlParamas)
{
DataSet ds = null;
try
{
con = new SqlConnection(connectionstring);
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
if (querytype.Equals("sp"))
cmd.CommandType = CommandType.StoredProcedure;
else
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 300;
if (objArrSqlParamas != null)
{
for(int idx=0;idx<objArrSqlParamas.Length;idx++)
cmd.Parameters.Add(objArrSqlParamas[idx]);
}
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cmd != null)
cmd.Dispose();
if (da != null)
da.Dispose();
if (con != null)
{
con.Dispose();
con.Close();
}
}
return ds;
}
}
Even though I am passing all the parameters to SP "SPLINV",I am getting below error in the GetData function.
System.Data.SqlClient.SqlException: Procedure or function 'SPLINV'
expects parameter '#ACTION', which was not supplied.
"SPLINV" Sp was created like below.
CREATE PROCEDURE SPLINV
(
#ACTION VARCHAR(50),
#USERID VARCHAR(100)
)
I just want to know why this issue happening even though I am passing all the parameters to SP and how to resolve this.

The problem is here :- if (querytype.Equals("sp"))
Equals is case sensitive. You are passing "SP" and checking for "sp". So the command get executed as text. Please go through the changed code.
private DataSet GetData(string clientconstr,string actionparam,string userid)
{
DataSet dsData = null;
SqlParameter[] objSqlParam = new SqlParameter[2];
objSqlParam[0] = new SqlParameter("#ACTION", SqlDbType.VarChar, 50);
objSqlParam[0].Value = actionparam;
objSqlParam[1] = new SqlParameter("#USERID", SqlDbType.VarChar, 100);
objSqlParam[1].Value = userid;
dbc = new dbClass(clientconstr);
dsData = dbc.ExecuteNonQuery("SPLINV", "SP", objSqlParam);
}
class dbClass
{
SqlCommand cmd = null;
SqlConnection con = null;
SqlDataAdapter da = null;
string connectionstring = "";
public dbClass(string conStr)
{
connectionstring = conStr;
}
public DataSet ExecuteNonQuery(string query, string querytype, SqlParameter[] objArrSqlParamas)
{
DataSet ds = null;
try
{
con = new SqlConnection(connectionstring);
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
if (querytype.Equals("SP"))
cmd.CommandType = CommandType.StoredProcedure;
else
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 300;
if (objArrSqlParamas != null)
{
for(int idx=0;idx<objArrSqlParamas.Length;idx++)
cmd.Parameters.Add(objArrSqlParamas[idx]);
}
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cmd != null)
cmd.Dispose();
if (da != null)
da.Dispose();
if (con != null)
{
con.Dispose();
con.Close();
}
}
return ds;
}
}

Have you tried setting the parameter directions to "Input"?
objSqlParam[0].Direction = ParameterDirection.Input;
objSqlParam[1].Direction = ParameterDirection.Input;

Related

C# InvalidOperationException when creating a new SqlDataAdapter

I`ve written some code to establish a connection to SQL Server, then execute select procedure to take all data from my data table in SQL server, but it throw a InvalidOperationException at the command of declare a new SqlDataAdapter, please help me to fix this error.
public class dBConnect
{
//create SQLconnection variable
private SqlConnection con;
//create default constructor that passing a string to con
public dBConnect()
{
try
{
con = new SqlConnection(#"Server=Trump\SQLEXPRESS;
Database=Demo;User Id=sa;Password = stevejobs;");
}
catch(Exception exCon)
{
Console.WriteLine("Unable to connect to database: {0}", exCon);
}
}
//create Select method to Pour the data into the DataTable
public DataTable SelectAll(string procName, SqlParameter[] para = null)
{
//create a DataTable to store Data from DB
DataTable dt = new DataTable();
//create SQLCommand
SqlCommand cmd = new SqlCommand(procName, con);
//declare that cmdType is sp
cmd.CommandType = CommandType.StoredProcedure;
//input parameter of cmd
if (para != null)
cmd.Parameters.AddRange(para);
//create dataAdapter object
//InvalidOperationException was thrown at here
SqlDataAdapter da = new SqlDataAdapter(cmd);
//declare that cmd is select command of da
da.SelectCommand = cmd;
//use try/catch/finally to establish a connection
try
{
con.Open();
da.Fill(dt);
}
catch(Exception sqlEx)
{
Console.WriteLine(#":Unable to establish a connection: {0}", sqlEx);
}
finally
{
con.Close();
con.Dispose();
}
return dt;
}
}
}
You should:
cmd.CommandText = "your Stored Procedure here.";
cmd.CommandType = CommandType.StoredProcedure;
//input parameter of cmd
if (para != null)
cmd.Parameters.AddRange(para);
//create dataAdapter object
Put your con.Open(); above
or
Just take a look at this steps
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
//sample stored procedure with parameter:
// "exec yourstoredProcedureName '" + param1+ "','" + param2+ "'";
cmd.CommandText = "Your Stored Procedure Here";
cmd.CommandType =CommandType.StoredProcedure;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
Cleaning up your code a bit here:
public DataTable SelectAll(string procName, SqlParameter[] para = null)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(procName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
if (para != null)
cmd.Parameters.AddRange(para);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
catch (Exception sqlEx)
{
Console.WriteLine(#":Unable to establish a connection: {0}", sqlEx);
}
return dt;
}

How to return default value when value is null or empty

How can I make the below code return zero if the returned value is null or empty. Also how can I return only the first record on the data table
private DataTable GetData(SqlCommand cmd)
{
gridoutofstock.DataBind();
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["AhlhaGowConnString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
You need to use SqlCommand.ExecuteScalar instead of the SqlDataAdapter, you are trying to retrive a single scalar value and not a DataSet.
Example :
static int GetOrderQuantity()
{
int quantity = 0;
string sql = "select sum(Quantity) from [dbo].Orderdetails ";
using (SqlConnection conn = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
quantity = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
//Handle exception
}
}
return quantity;
}

Fail update database from DataGridView

This WinForms project has the following code:
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EbosPr.Properties.Settings.Database1ConnectionString1"].ConnectionString);
SqlCommand scmd = new SqlCommand("Select * From CustCalls ", conn);
SqlDataAdapter sda = new SqlDataAdapter(scmd);
sda.Fill(ds);
DataTable dt = ds.Tables[0];
this.dataGridView1.BindingContext[dt].EndCurrentEdit();
SqlCommandBuilder myBuilder = new SqlCommandBuilder(sda);
myBuilder.GetUpdateCommand();
sda.UpdateCommand = myBuilder.GetUpdateCommand();
sda.Update(dt);
It doesn't update the database and there is no error. How can this be improved?
I have the following code in production in a small internal utility and it works like a charme:
public int UpdateSQLDataTable(string connectionString, string TableName, DataTable dtSource)
{
using (SqlConnection sConn = new SqlConnection(connectionString))
{
sConn.Open();
var transaction = sConn.BeginTransaction();
try
{
SqlCommand command = sConn.CreateCommand();
command.Transaction = transaction;
command.CommandText = string.Format("SELECT TOP 1 * FROM dbo.[{0}] WITH (NOLOCK)", TableName);
command.CommandType = CommandType.Text;
// timeout in seconds...
command.CommandTimeout = 30;
SqlDataAdapter sAdp = new SqlDataAdapter(command);
SqlCommandBuilder sCMDB = new SqlCommandBuilder(sAdp);
int affectedRecords = sAdp.Update(dtSource);
transaction.Commit();
return affectedRecords;
}
catch (Exception /* exp */)
{
transaction.Rollback();
throw;
}
}
}
use a dataTable instead of a DataSet .. that worked for me

How to get data from stored sql procedure in dataset with SqlDataAdapter?

Is this good approach to get data from stored procedure? For example procedure is making select * from base. Here is my code but I need help with dataset and adapter:
public static DataSet Osvezi(string naziv_tablice)
{
SqlCommand cmd = null;
DataSet dataset = null;
SqlConnection konekcija = new SqlConnection(ConfigurationManager.AppSettings["skripta"]);
if (konekcija != null)
{
try
{
if (konekcija.State == ConnectionState.Closed)
konekcija.Open();
cmd = new SqlCommand();
cmd.Connection = konekcija;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Osvezi";
cmd.Parameters.Add(new SqlParameter("#tablica", SqlDbType.Int)).Value = naziv_tablice;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Fill the DataSet using default values for DataTable names, etc
da.Fill(dataset);
return dataset;
}
catch (Exception ee)
{
//Obravnava napak
}
finally
{
konekcija.Close();
konekcija.Dispose();
cmd.Dispose();
}
return dataset;
}
return dataset;
}
Try this one instead:
public static DataSet Osvezi(string naziv_tablice)
{
try
{
using (SqlConnection konekcija = new SqlConnection(ConfigurationManager.AppSettings["skripta"]))
{
konekcija.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = konekcija;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Osvezi";
cmd.Parameters.AddWithValue("#tablica", naziv_tablice??DBNull.Value);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
// Fill the DataSet using default values for DataTable names, etc
DataSet dataset = new DataSet();
da.Fill(dataset);
return dataset;
}
}
}
}
catch (Exception ee)
{
//Obravnava napak
}
return null;
}
Please correct the following.
You don't need to open the connection.
There shouldn't be any command.ExecuteNonQuery.
The parameter in the method is string but the datatype of SqlParameter is SqlDbType.Int.

How can I return dataset perfectly from SQL?

I try to write a winform application:
I dislike below codes:
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
Above part of codes looks unsufficient.How can I best loading dataset?
public class LoadDataset
{
public DataSet GetAllData(string sp)
{
return LoadSQL(sp);
}
private DataSet LoadSQL(string sp)
{
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand(sp, con);
DataSet ds;
try
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
finally
{
con.Dispose();
cmd.Dispose();
}
}
}
Here is a simple function I converted from VB to C# (http://www.developerfusion.com/tools/convert/vb-to-csharp/). I use this extensively.
Simple wrapper function to help return a dataset from and SQL statement via an existing connection.
This should have performance improvements over re-connected via a connection string each time. Wraps any SQL errors in to a custom format.
public System.Data.DataSet GetDataSet(string sqlStatement, System.Data.SqlClient.SqlConnection connection)
{
System.Data.DataSet functionReturnValue = default(System.Data.DataSet);
if (connection == null) {
throw new ArgumentNullException("connection");
}
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter();
System.Data.DataSet dset = new System.Data.DataSet();
try {
// Connect to the database
if (connection.State != ConnectionState.Open) {
connection.Open();
}
if (connection.State != ConnectionState.Open) {
throw new MyCustomException("Connection currently {0} when it should be open.", connection.State));
}
// Create a command connection
cmd = new System.Data.SqlClient.SqlCommand();
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStatement;
}
//.ExecuteReader() 'Forward only Dataset
// Create a data adapter to store the inforamtion
adp = new System.Data.SqlClient.SqlDataAdapter();
dset = new DataSet();
{
adp.SelectCommand = cmd;
adp.Fill(dset, "Results");
}
// Return the resulting dataset to the calling application
functionReturnValue = dset;
}
catch (System.Data.SqlClient.SqlException objSE) {
functionReturnValue = null;
// Let the calling function known they stuffed up and give them the SQL to help out.
throw new JDDataException(System.String.Format("SQL :- {0}.", sqlStatement), objSE);
}
finally {
if ((cmd != null)) cmd = null;
if ((adp != null)) adp = null;
if ((dset != null)) dset = null;
}
return functionReturnValue;
}
public string GetSqlConnection()
{
return System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
}
public DataSet getDataSet(string sql)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(GetSqlConnection());
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
conn.Close();
conn.Dispose();
da.Dispose();
return ds;
}

Categories