My application needs to get data from a store procedure. In a query program the stored procedure works fine;
exec MyStoredProdure #Prama1 = '01'
In WPF it times out. Here is my code;
using (SqlConnection con = new SqlConnection(ConString))
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Prama1", "01");
cmd.CommandText = "MyStoredProdure";
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("MyStoredProdure");
sda.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
//Do code
}
con.Close();
}
It is timing out right on sda.Fill(dt). It should be noted that Select and inserts work perfectly fine.
I believe you're missing the sda.SelectCommand = cmd; before the fill.
How to use a DataAdapter with stored procedure and parameter
Related
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(Global.ConnectionString());
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
SqlDataReader drReader = null;
cmd = new SqlCommand();
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spIndustryDataSelect";
cmd.Parameters.AddWithValue("#iiProcessType", 1);
drReader = cmd.ExecuteReader();
conn.Close();
da.SelectCommand = new SqlCommand();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(dt);
lstIndustry.DataSource = dt;
lstIndustry.DataBind();
I using this c# code to fill the lstIndustry asp ListView, but it take a minute time because it has a thousand of rows and i need to select all, is there any method to fill the list in fast time?
You can create pagination with Using Take And Skip for improve performance
You can add Index on Table if You have where in sp
public Section SectionView(object id, SqlConnection conn)
{
using (SqlCommand cmd = new SqlCommand())
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataAdapter sqlda = new SqlDataAdapter("TMR_SECTION_VIEW", conn);
SqlDataAdapter da = new SqlDataAdapter("data", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "TMR_SECTION_VIEW";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#sectionID", id.ToString);
cmd.Parameters.AddWithValue("#name", name);
da.SelectCommand = cmd;
DataTable dt = new DataTable();
DataTable dtbl = new DataTable();
sqlda.Fill(dtbl);
cmd.ExecuteNonQuery();
return id;
}
}
My stored procedure is:
ALTER PROCEDURE [dbo].[TMR_SECTION_VIEW]
#sectionID int, #name varchar(100)
AS
BEGIN
SELECT *
FROM Section
WHERE sectionid = #sectionID
END
You have things a little bit out of order...
You should be specifying the command name on the SqlCommand (not the DataAdapter) and you should be telling the DataAdapter to use the SqlCommand.
I'd change this to allow you to specify the Stored Procedure name as a parameter when you call the function:
public Section SectionView(object id, SqlConnection conn, string sql = String.Empty)
{
if (!String.IsNullOrEmpty(sql))
{
if (conn.State == ConnectionState.Closed) conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#sectionID", id.ToString);
cmd.Parameters.AddWithValue("#name", name);
SqlDataAdapter da = new SqlDataAdapter
{ SelectCommand = cmd };
DataTable dtbl = new DataTable();
sqlda.Fill(dtbl);
return id;
}
}
}
You duplicated a lot of things (like setting the CommandType of your SqlCommand) and you created DataTable dt without using it, so I removed it from the sample in my answer.
So what's happening here is that you're specifying a sql string as a parameter (which can be a normal SQL query or a stored procedure) and you're building a SqlCommand with it that has parameters.
Using that SqlCommand, you're creating a DataAdapter having the SqlCommand as its SelectCommand and then you're using that DataAdapter to fill the DataTable.
NOTE: You don't need to execute SqlCommand.ExecuteNonQuery() when retrieving data as the DataAdapter.Fill() function basically does that for you.
ExecuteNonQuery would be useful when inserting or updating data - not when reading data.
I have this code that is suppose to get me the last registered MemberId from column but I cant get it to work, what have I got wrong?
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT top 1 * FROM Medleminfo ORDER BY MemberId desc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
last_id = Convert.ToInt32(dr["MemberId"].ToString());
}
return last_id;
Output last_id is supposed to be used in this method:
public DataTable display_tiger_info(int member_id)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT Medleminfo.MemberId, Medleminfo.Förnamn, Medleminfo.Efternamn,
Medleminfo.Adress, Medleminfo.Telefon, Tigerinfo.Tigernamn,Tigerinfo.Födelsedatum
FROM Medleminfo, Tigerinfo WHERE Medleminfo.MemberId = Tigerinfo.OwnerID ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
Why not just use the 'Max' function? This is assuming that your looking for the largest number in the sequence. The way your question is worded though would suggest that you should have a date column to search by instead. Also if you want just one result then try execute scalar instead of putting it into a data table and going through all that extra work.
int id = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("Select Max(MemberId) from Medleminfo", connection))
{
id = (int)command.ExecuteScalar();
}
}
I think your issues is probably cmd.ExecuteNonQuery() according to the msdn SqlCommand.ExecuteNonQuery Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
You will probably be wanting to use ExecuteReader in something like the following
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//All you want is the member Id why get all the columns
cmd.CommandText = "SELECT top 1 MemberId FROM Medleminfo ORDER BY MemberId desc";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
last_id = Convert.ToInt32( reader[0]));
}
return last_id;
UPDATE: This code might solve your problem but I did not identify the issue correctly cmd.ExecuteNonQuery() should be removed it is not doing anything. adapter.Fill() should be executing the command and I do not know why you are not getting the expected response.
I am very confuse with following code .This is also inserting data into table with insert in Stored procedure, even this has not executenonquery(),executescalar() or adapter.insert like methods...
then how it is possible
public DataSet GetDataSet(string spName, System.Collections.Hashtable hst)
{
cmd.CommandTimeout = 220;
con = new SqlConnection();
cmd = new SqlCommand();
con.ConnectionString = constr;
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
con.Open();
if (hst != null)
if (hst.Count > 0)
AttachParameters(cmd, hst);
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(dataset);
con.Close();
return dataset;
}
This method just Retrieve the data u wanted and storing it into your dataset
adapter.Fill(dataset); this part is used to fill your dataset with the data u populate out.
So as to pass to your stored procedure so technically your stored procedure is doing the insert not this.In your stored procedure u should have a insert statement
If the stored procedure is in your database stored procedure folder u do not need to use adapter as it will run internally to retrieve the results
something like this
INSERT INTO msdb.dbo.db(db)
VALUES (#dbdata)
I am facing a little problem in my code to add data to sql database attached with my program in ASP.net/C#. Here's code:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
SqlConnection cnn = new SqlConnection(ConnectionString);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select Id from TableName";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " TableName ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["TableName"].NewRow();
drow["Id"] = TextBox1.Text;
ds.Tables["TableName "].Rows.Add(drow);
da.Update(ds, " TableName ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
Even when I entered any integer value to the text box, it shows an error message that object is not set to an instance on code:
DataRow drow = ds.Tables["TableName"].NewRow();
Please guide.
Thanks.
This seems like a very bad way of inserting data. Have you looked at the Entity Framework or Linq2Sql? Alternatively you could just use a standard SqlCommand and set the CommandText yourself.
Any of these would provide a cleaner solution.
Eg: With ADO.NET (Connecting to SQLite):
var conn = new SQLiteConnection(string.Format(Constants.SQLiteConnectionString, "db.db3"));
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction()) {
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "INSERT INTO TableName (Id) VALUES (#Id)";
cmd.Parameters.AddWithValue("#Id", someTextVariable);
cmd.ExecuteNonQuery();
}
}