error: not all code path returns a value,
i'm trying to return a dataset from function but getting this error,
code:
public partial class crystalReport_manual : System.Web.UI.Page
{
String conStr = WebConfigurationManager.ConnectionStrings["LoginDatabaseConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
DataSet1 ds = Dataset_load("Select * from login");
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("CrystalReport.rpt"));
rd.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rd;
}
public DataSet1 Dataset_load(String query)
{
SqlConnection sqlcon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom);
// DataSet ds = new DataSet("CRDataSet");
try
{
sqlcon.Open();
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataSet1 ds = new DataSet1();
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
return ds;
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
sqlcon.Close();
}
}
What if an exception occur, your catch or finally block should return some value.
Since you are only closing the connection in finally you can use using block like:
public DataSet1 Dataset_load(String query)
{
DataSet1 ds = new DataSet1();
using(SqlConnection sqlcon = new SqlConnection(conStr))
using(SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon))
using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom))
{
try
{
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
return ds;
}
catch (SqlException se)
{
Response.Write(se.Message);
return null;
}
catch (Exception exc)
{
Response.Write(exc.Message);
return null;
}
}
}
using internally translates to try-finally block, and works with those which implements IDisposable, in finally block it calls the Dispose method, since SqlConnection, SqlCommand, and SqlDataAdapter, all implements IDisposable with using statement it will call Dispose at the end which would close the connection.
public DataSet1 Dataset_load(String query)
{
DataSet1 ds = new DataSet1();
using(SqlConnection sqlcon = new SqlConnection(conStr))
using(SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon))
using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom))
{
try
{
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
//return ds;
}
catch (SqlException se)
{
Response.Write(se.Message);
//return null;
}
catch (Exception exc)
{
Response.Write(exc.Message);
//return null;
}
}
return ds;
}
Building off the previous user's response, if an empty DataSet is returned at the end of your using statement, you can always check ds.Tables.Count to see if anything was returned. Otherwise you can use the logic above and null check
Related
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;
}
When I try to use the method GetCities(), it says:
Fill: SelectCommand.Connection property has not been initialized.
Can anyone please advise on what to do?
public class CitiesService
{
public DataSet DS;
public OleDbConnection myConnection;
public OleDbDataAdapter adapter;
public OleDbDataAdapter adapter2;
public CitiesService()
{
}
public DataSet GetCities()
{
OleDbCommand myCmd = new OleDbCommand("SPtblCities", myConnection);
myCmd.CommandType = CommandType.StoredProcedure;
OleDbDataAdapter Adapter = new OleDbDataAdapter();
Adapter.SelectCommand = myCmd;
DataSet dataSet = new DataSet();
try
{
Adapter.Fill(dataSet, "tblCities");
dataSet.Tables["tblCities"].PrimaryKey = new DataColumn[]
{
dataSet.Tables["tblCities"].Columns["CityID"]
};
}
catch (OleDbException ex)
{
throw ex;
}
return dataSet;
}
}
Yes, the connection was not initialized, it is null.
Replace
public OleDbConnection myConnection;
with
public OleDbConnection myConnection = new OleDbConnection(ConnectionString);
or in the method:
myConnection = new OleDbConnection(ConnectionString);
OleDbCommand myCmd = new OleDbCommand("SPtblCities", myConnection);
I would recommend you use this pattern and remember that some of these objects are disposable.
public class CitiesService
{
public DataSet DS;
public OleDbConnection myConnection;
public OleDbDataAdapter adapter;
public OleDbDataAdapter adapter2;
public CitiesService()
{
}
public DataSet GetCities()
{
using (DataSet dataSet = new DataSet())
{
using (OleDbConnection myConnection = new OleDbConnection(ConnectionString))
{
myConnection.Open();
using (OleDbCommand myCmd = myConnection.CreateCommand())
{
myCmd.CommandType = CommandType.StoredProcedure;
using (OleDbDataAdapter Adapter = new OleDbDataAdapter())
{
Adapter.SelectCommand = myCmd;
try
{
Adapter.Fill(dataSet, "tblCities");
dataSet.Tables["tblCities"].PrimaryKey = new DataColumn[] { dataSet.Tables["tblCities"].Columns["CityID"] };
}
catch (OleDbException ex)
{
throw ex;
}
}
}
myConnection.Close();
}
return dataSet;
}
}
}
I have defined the following function which would return 3 columns from table.
public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = new DataSet();
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
adaptor.Fill(ds);
sqlConnection.Close();
return ds;
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
}
But when I'm trying to build it, I'm getting the error:
Error 172 'GetFunc()': not all code paths return a value
I'm confused on where am I going wrong. Can someone guide me through?
In the try block You have given a return type while in the catch block there is no return type.
This error usually occurs when the compiler does not find an appropriate return values.
Try returning ds in catch
But make sure that further in your logic you check ds for a null check
public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = new DataSet();
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
adaptor.Fill(ds);
sqlConnection.Close();
return ds;
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
return null;
}
Not all paths of your code return value, but have to. If DB_SUCCESS_CONNECT!=iRet you won't return result. Try returning some default value, maybe null like above. Another problem is that you are not returning value if exception is thrown. When exception is thrown you are disconnecting and not returning any value.
it is because there is no return path in case :- DB_SUCCESS_CONNECT != iRet
If an exception is being thrown within the try ... catch block there is no return value specified.
Add:
return ds;
at the end of your function after the catch block.
You have only return statements in try block which is not assured that it will always executed due to exception what compiler assumes. Add another return statement that returns null or dataset out of try then you wont get error. You can have only one return statement instead of two or three.
public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = null;
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
ds = new DataSet();
adaptor.Fill(ds);
sqlConnection.Close();
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
return ds;
}
your code fail because you only return value if the condition true. if condition fail or if some exception happen there is nothing returning from your method.
and also please note, you are not handling connection properly. You need to close or dispose connection object. I would change your method as below
public DataSet GetFunc()
{
string strQuery = "Select ID, Did, FirstName from Users";
DataSet ds = new DataSet();
using (var sqlConnection = new SqlConnection())
using (var sqlCommand = new SqlCommand(strQuery, sqlConnection))
using (var adaptor = new SqlDataAdapter(sqlCommand))
{
adaptor.Fill(ds);
}
return ds;
}
Place return statement after try and catch block, try with the code below:
public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = new DataSet();
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
adaptor.Fill(ds);
sqlConnection.Close();
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
return ds;
}
If function has return type it should return something in all the situation, so function should have return value for Try block as well as for Catch block
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.
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;
}