What is my method missing? It is not returning the data table.
public DataTable GetHotelReportData(int _ratpropid) {
var _connectionString = _isDevelopment ? CommonTypes.Dev : CommonTypes.Prod;
DataTable dt = new DataTable();
dt.Clear();
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("ww.HotelRpt_spGenerateData2018", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#RatPropId", _ratpropid);
SqlDataAdapter da = new SqlDataAdapter();
try {
da.SelectCommand = cmd;
da.Fill(dt);
}
catch (Exception _ex) {
new ErrorLogging().Log(_ex);
}
finally {
conn.Close();
da.Dispose();
cmd.Dispose();
}
return dt;
}
Try cutting the data adapter out and just using the command. No need for an adapter as far as I can tell:
public DataTable GetHotelReportData(int _ratpropid) {
var _connectionString = _isDevelopment ? CommonTypes.Dev : CommonTypes.Prod;
DataTable dt = new DataTable();
dt.Clear();
SqlConnection conn = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand("ww.HotelRpt_spGenerateData2018", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#RatPropId", _ratpropid);
try {
conn.Open();
dt.Load(cmd.ExecuteReader);
return dt;
}
catch (Exception _ex) {
new ErrorLogging().Log(_ex);
}
finally {
conn.Close();
cmd.Dispose();
}
}
If that doesn't work, try executing your stored procedure natively in SSMS (or another DBMS) to see if you get any results there.
Related
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.
well, I've done everything on my behalf just to solve this problem. i'm trying to print the data from my database using grid view in asp.net using c# codes. can anyone tell me whats wrong and how to improve my codes. thank you.
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
You must fill the DataSet with data like this :
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "TableName");
GridView1.DataSource = ds.Tables["TableName"];
GridView1.DataBind();
You're assigning an empty DataSet to your DataSource, without filling the results of your DataReader into the DataSet/DataTable.
using (MySqlConnection con = new MySqlConnection(""))
{
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
try
{
DataTable dt = new DataTable();
using (MySqlDataReader reader1 = cmd.ExecuteReader())
{
dt.Load(reader1);
}
GridView1.DataSource = dt ;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}
I have more than one function which simply fetches data from DB. The difference among the function is the stored procedure name (uspLoadStudents,uspLoadMarks). To optimize, make it as one function and passes the SP.
public DataSet LoadSubjects()
{
string SqlDBConnection = Utils.GetConnectionString();
DataSet ds = new DataSet();
SqlConnection sqlConn = new SqlConnection(SqlDBConnection);
SqlCommand sqlCmd = new SqlCommand("uspLoadSubjects", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(sqlCmd.ExecuteReader());
ds.Tables.Add(dt);
sqlConn.Close();
return ds;
}
Information like sql command, stored procedure name, should be part of your Data Access Layer, instead it is a helper class inside the data access layer. Try this:
public static class DALHelper
{
public static DataSet ExecuteProcedure(string procedureName)
{
string sqlDBConnection = Utils.GetConnectionString();
DataSet ds = new DataSet();
using (SqlConnection sqlConn = new SqlConnection(sqlDBConnection))
{
using(SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConn))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
try
{
sqlConn.Open();
using (var adapter = new SqlDataAdpter(sqlCmd))
{
adapter.Fill(ds);
}
}
catch
{
throw;
}
finally
{
sqlConn.Close();
}
}
}
return ds;
}
}
Implement a method to use this helper, for sample:
public DataSet LoadSubjects()
{
return DALHelper.ExecuteProcedure("uspLoadStudents");
}
This?
public DataSet ExecProc(string procName)
{
string SqlDBConnection = Utils.GetConnectionString();
DataSet ds = new DataSet();
SqlConnection sqlConn = new SqlConnection(SqlDBConnection);
SqlCommand sqlCmd = new SqlCommand(procName, sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(sqlCmd.ExecuteReader());
ds.Tables.Add(dt);
sqlConn.Close();
return ds;
}
try this
public static DataSet getDataSet(string sp_name, string[] param_names, object[] param_values)
{
SqlDataAdapter sqlda = new SqlDataAdapter();
SqlCommand sqlcmd = new SqlCommand();
DataSet set = new DataSet();
try
{
sqlcmd.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = sp_name;
sqlda.SelectCommand = sqlcmd;
sqlda.Fill(set);
}
catch (Exception ex)
{
}
finally
{
if (sqlcmd.Connection.State == ConnectionState.Open)
sqlcmd.Connection.Close();
}
return set;
}
How is it I can upload a 20+ mb file to a webserver, but have it timeout when I try to download it? I would think the upload would timeout as well.
Both are using ado.net sqlclient. The event log shows SqlException timeout occurred when attempting to download.
This article looks like a possible lead. But again, why wouldn't it timeout on the upload?
public DataTable ExecuteDataTable(string sql)
{
SqlConnection conn = new SqlConnection();
DataTable dt;
try
{
conn.Open();
SqlCommand dateformatcmd = new SqlCommand("set dateformat " + myDateFormat, conn);
dateformatcmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
SqlCommand cmd = new SqlCommand(sql, conn);
//Walk through the parameters
foreach (string name in param.Keys)
{
cmd.Parameters.Add(new SqlParameter(name, param[name]));
}
da.SelectCommand = cmd;
dt = new DataTable();
da.Fill(dt);
}
catch (SqlException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return dt;
}
I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling).
This is what I am doing.Thanks in advance.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
It shows connected when i comment the line sda.Fill(dt);
Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
You don't assign the command any connection. You open the connection then create a command, but don't link the two.
Try something like:
SqlConnection conn = new SqlConnection(#"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();
string sql= "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
Assign Connection Object to SqlCommand Object.
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
//Perfom desired Action
}
Add thisConnection as 2nd parameter in
Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)
try {
string connectionstring = "#"
Server = (local) Database = Sample_dbTrusted_Connection = Yes;
"";
SqlConnection thisConnection = new SqlConnection(connectionstring);
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);`
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
} catch {
MessageBox.Show("db error");
}
I use this code with Oracle and hope it will help you.
First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;
And using the following code
try
{
string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
using (OracleConnection connection = new OracleConnection(MyConString))
{
connection.Open();
sqldb1 = "select * from DEMO_CUSTOMERS;";
using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
{
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
da.Fill(dt);
db1.ItemsSource = dt.DefaultView;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
XAML code:
<DockPanel>
<DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1" AutoGenerateColumns="True" >
</DataGrid>
</DockPanel>
public DataTable Execute(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
sda.SelectCommand = command;
command.Connection = connection;
connection.Open();
sda.Fill(dt);
connection.Close();
if (dt != null && dt.Columns.Count > 0)
return dt;
else
return null;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
else
{
Console.WriteLine("Network is disconnect");
return null;
}
return null;
}
or :
public void ExecuteNonQuery(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}