SQL Command Datareader

Jul 31, 2007

I have the following SQL statement in the DataReader.SQLCommand.

select * from myTable where DataEdited > 'some hard coded date data'

I want to read the above 'some hard coded date data' from a table sitting in different database which is not the same server where the DataReader is connected.

How to do that?

I can populate the 'some hard coded date data' to a SSIS variable but do not know how to embed that in the SQL statement.

Thank you for your thoughts.

Smith

View 9 Replies


ADVERTISEMENT

Error: There Is Already An Open DataReader Associated With This Command

Nov 1, 2006

HiI'm trying to loop through all the records in a recordset and perform a database update within the loop. The problem is that you can't have more than one datareader open at the same time. How should I be doing this? cmdPhoto = New SqlCommand("select AuthorityID,AuthorityName,PREF From qryStaffSearch where AuthorityType='User' Order by AuthorityName", conWhitt)conWhitt.Open()dtrPhoto = cmdPhoto.ExecuteReaderWhile dtrPhoto.Read()If Not File.Exists("D:WhittNetLiveWebimagesstaffphotospat_images_resize" & dtrPhoto("PRef") & ".jpg") ThencmdUpdate = New SqlCommand("Update tblAuthority Set NoPhoto = 1 Where AuthorityID =" & dtrPhoto("AuthorityID"), conWhitt)cmdUpdate.ExecuteNonQuery()End IfEnd WhileThanks

View 7 Replies View Related

There Is Already An Open DataReader Associated With This Command Which Must Be Closed

Oct 15, 2007

I have gathered from reading online that I need to create a 2nd connection to SQL Server if I want to insert records into the database while in a "while (reader.Read())" loop.

I am trying to make my code as generic as possible, and I don't want to have to re-input the connection string at this point in my code. Is there a way to generate a new connection based on the existing open one? Or should I just create 2 connections up front and carry them around with me like I do for the 1 connection now?

Thanks.

View 7 Replies View Related

Connection, DataReader And Command Question

Apr 2, 2008

I have a multiple form project for a Windows CE 5.0 device (Symbol MC3000) written in VB.NET (Visual Studio 2005) using SQL Server Compact 3.5.

If I create the database on the SD Card, the program works fine until the unit is "suspended". When the power resumes, I can still continue to work and save/access data in the database as long as I do not go to another form. If I go to another form, I get an access violation error (0xC0000005).

If the database is installed in main memory the prorgam works properly even after the power is cycled.

Unfortunately, due to the memory size restrictions on the device, there are cases where the database needs to be stored on the SD Card.

Currently the program uses a single "global" SQLCeConnection and the connection is closed prior to the device being powered off. However, each procedure/event in the program uses it's own SQLCeCommand and SQLCeDataReader objects (which are created and closed/disposed prior to the end of the procedure).

I have tried everything I can think of, including OS updates, .NET Compact Framework 2.0 updates and modifications to the program to correct this, but the results are the same.

Would creating a global SQLDataReader and SQLCeCommand object help with this issue or should the way that this is currently being handled work?

View 4 Replies View Related

How To Fix This Error? (There Is Already An Open DataReader Associated With This Command Which Must Be Closed First.)

Jun 26, 2007

This is my code:1 If Session("ctr") = False Then
2
3 Connect()
4
5 SQL = "SELECT * FROM counter"
6 SQL = SQL & " WHERE ipaddress='" & Request.ServerVariables("REMOTE_ADDR") & "'"
7 dbRead()
8
9 If dbReader.HasRows = True Then
10
11 dbReader.Read()
12 hits = dbReader("hits")
13 hits = hits + 1
14 dbClose()
15
16 SQL = "UPDATE counter SET hits=" & hits
17 SQL = SQL & " WHERE ipaddress='" & Request.ServerVariables("REMOTE_ADDR") & "'"
18 dbExecute()
19
20 Else
21
22 SQL = "INSERT INTO counter(ipaddress,hits)"
23 SQL = SQL & " VALUES('" & Request.ServerVariables("REMOTE_ADDR") & "',1)"
24 dbExecute()
25
26 End If
27
28 Session("ctr") = True
29
30 End If
 1 Public Sub Connect()
2 Conn = New SqlConnection("Initial Catalog=NURSETEST;User Id=sa;Password=sa;Data Source=KSNCRUZ")
3 If Conn.State = ConnectionState.Open Then
4 Conn.Close()
5 End If
6 Conn.Open()
7 End Sub
8
9 Public Sub Close()
10 Conn.Close()
11 Conn = Nothing
12 End Sub
13
14 Public Sub dbExecute()
15 dbCommand = New SqlCommand(SQL, Conn)
16 dbCommand.ExecuteNonQuery()
17 End Sub
18
19 Public Sub dbRead()
20 dbCommand = New SqlCommand(SQL, Conn)
21 dbReader = dbCommand.ExecuteReader
22 End Sub
23
24 Public Sub dbClose()
25 SQL = ""
26 dbReader.Close()
27 End Sub
 

View 2 Replies View Related

Exception:There Is An Open DataReader Associated With This Command Which Must Be Closed First.

May 3, 2008

the class code:
Dataase.cs: using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using System.Data.SqlClient; using System.Data.Common; using System.Web; /// <summary> /// Summary description for DataBase /// </summary> public class DataBase { private SqlConnection con=new SqlConnection(); private void Open() { if (con==null) { con = new SqlConnection("Data Source=58.17.30.81;Initial Catalog=a1230192748;Persist Security Info=True;User ID=a1230192748;Password=***"); } if (con.State == System.Data.ConnectionState.Closed) { con.ConnectionString = "Data Source=58.17.30.81;Initial Catalog=a1230192748;Persist Security Info=True;User ID=a1230192748;Password=****"; con.Open(); } } public void Close() { if (con != null && con.State != System.Data.ConnectionState.Open) con.Close(); } public DataBase() { // // TODO: Add constructor logic here // } public string liuyan(string id,string sign) { string com=string.Empty; switch(sign) { case "xiaobiaoti": com="Select subject from liuyan where liuyanid='"+id+"'"; break; case "def_message": com="Select message from liuyan where liuyanid='"+id+"'"; break; } SqlCommand myCommand=new SqlCommand(com,con); Open(); try { SqlDataReader sdr=myCommand.ExecuteReader(); if (sdr.Read()) { return sdr[0].ToString(); } else { return ""; } sdr.Close();    //what i have written.} catch (Exception ex) { HttpContext.Current.Response.Write("<script>alert('error:" + ex.Message + "')</script>"); return ""; } finally { myCommand.Dispose(); Close(); } } }
 
it was instantiated once in  aspx.cs code.I invoke liuyan(string id,string sign) twice.The first one is OK and the second one makes an exception.
 

View 3 Replies View Related

Datareader Destination As Source For Other Datareader Source ?

Aug 30, 2006

HI!

as far as I know from docs and forum datareader is for .NET data in memory. So if a use a complex dataflow to build up some data and want to use this in other dataflow componens - could i use data datareader source in the fist dataflow and then use a datareader souce in the second dataflow do read the inmemoty data from fist transform to do fursther cals ?

how to pass in memory data from one dataflow to the next one (i do not want to rebuild the logic in each dataflow to build up data data ?

Is there a way to do this ? and is the datareader the proper component ? (because its the one and only inmemory i guess, utherwise i need to write to temp table and read from temp table in next step) (I have only found examples fro .NET VB or C# programms to read a datareader, but how to do this in SSIS directly in the next dataflow?

THANKS, HANNES

View 7 Replies View Related

Defining Command,commandtype And Connectionstring For SELECT Command Is Not Similar To INSERT And UPDATE

Feb 23, 2007

i am using visual web developer 2005 and SQL 2005 with VB as the code behindi am using INSERT command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").ToString()        test.InsertCommandType = SqlDataSourceCommandType.Text        test.InsertCommand = "INSERT INTO try (roll,name, age, email) VALUES (@roll,@name, @age, @email) "                  test.InsertParameters.Add("roll", TextBox1.Text)        test.InsertParameters.Add("name", TextBox2.Text)        test.InsertParameters.Add("age", TextBox3.Text)        test.InsertParameters.Add("email", TextBox4.Text)        test.Insert() i am using UPDATE command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString()        test.UpdateCommandType = SqlDataSourceCommandType.Text        test.UpdateCommand = "UPDATE try SET name = '" + myname + "' , age = '" + myage + "' , email = '" + myemail + "' WHERE roll                                                         123 "        test.Update()but i have to use the SELECT command like this which is completely different from INSERT and  UPDATE commands   Dim tblData As New Data.DataTable()         Dim conn As New Data.SqlClient.SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated                                                                                Security=True;User Instance=True")   Dim Command As New Data.SqlClient.SqlCommand("SELECT * FROM try WHERE age = '100' ", conn)   Dim da As New Data.SqlClient.SqlDataAdapter(Command)   da.Fill(tblData)   conn.Close()                   TextBox4.Text = tblData.Rows(1).Item("name").ToString()        TextBox5.Text = tblData.Rows(1).Item("age").ToString()        TextBox6.Text = tblData.Rows(1).Item("email").ToString()       for INSERT and UPDATE commands defining the command,commandtype and connectionstring is samebut for the SELECT command it is completely different. why ?can i define the command,commandtype and connectionstring for SELECT command similar to INSERT and UPDATE ?if its possible how to do ?please help me

View 2 Replies View Related

Using A Variable In SSIS - Error - Command Text Was Not Set For The Command Object..

Nov 4, 2006

Hi All,

i am using a OLE DB Source in my dataflow component and want to select rows from the source based on the Name I enter during execution time. I have created two variables,

enterName - String packageLevel (will store the name I enter)

myVar - String packageLevel. (to store the query)

I am assigning this query to the myVar variable, "Select * from db.Users where (UsrName = " + @[User::enterName] + " )"

Now in the OLE Db source, I have selected as Sql Command from Variable, and I am getting the variable, enterName,. I select that and when I click on OK am getting this error.

Error at Data Flow Task [OLE DB Source [1]]: An OLE DB error has occurred. Error code: 0x80040E0C.
An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E0C Description: "Command text was not set for the command object.".

Can Someone guide me whr am going wrong?

myVar variable, i have set the ExecuteAsExpression Property to true too.

Please let me know where am going wrong?

Thanks in advance.








View 12 Replies View Related

Do Somebody Know How Long (in Chars) Script(command) Can Be Solved By SQL Command?

Aug 30, 2004

Do somebody know how long (in chars) script(command) can be solved by SQL Command?
Thanks

View 1 Replies View Related

What Command Is Used To Get Back The Privileges Offered By The GRANT Command?

Mar 10, 2007

reply.

View 1 Replies View Related

Command Text Was Not Set For The Command Object Error

Sep 19, 2006

Hi. I am writing a program in C# to migrate data from a Foxpro database to an SQL Server 2005 Express database. The package is being created programmatically. I am creating a separate data flow for each Foxpro table. It seems to be doing it ok but I am getting the following error message at the package validation stage:

Description: An OLE DB Error has occured. Error code: 0x80040E0C.

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E0C Description: "Command text was not set for the command object".

.........

Description: "component "OLE DB Destination" (22)" failed validation and returned validation status "VS_ISBROKEN".

This is the first time I am writing such code and I there must be something I am not doing correct but can't seem to figure it out. Any help will be highly appreciated. My code is as below:

private bool BuildPackage()

{




// Create the package object

oPackage = new Package();

// Create connections for the Foxpro and SQL Server data

Connections oPkgConns = oPackage.Connections;

// Foxpro Connection

ConnectionManager oFoxConn = oPkgConns.Add("OLEDB");

oFoxConn.ConnectionString = sSourceConnString; // Created elsewhere

oFoxConn.Name = "SourceConnectionOLEDB";

oFoxConn.Description = "OLEDB Connection For Foxpro Database";

// SQL Server Connection

ConnectionManager oSQLConn = oPkgConns.Add("OLEDB");

oSQLConn.ConnectionString = sTargetConnString; // Created elsewhere

oSQLConn.Name = "DestinationConnectionOLEDB";

oSQLConn.Description = "OLEDB Connection For SQL Server Database";

// Add Prepare SQL Task

Executable exSQLTask = oPackage.Executables.Add("STOCK:SQLTask");

TaskHost thSQLTask = exSQLTask as TaskHost;

thSQLTask.Properties["Connection"].SetValue(thSQLTask, "oSQLConn");

thSQLTask.Properties["DelayValidation"].SetValue(thSQLTask, true);

thSQLTask.Properties["ResultSetType"].SetValue(thSQLTask, ResultSetType.ResultSetType_None);

thSQLTask.Properties["SqlStatementSource"].SetValue(thSQLTask, @"C:LPFMigrateLPF_Script.sql");

thSQLTask.Properties["SqlStatementSourceType"].SetValue(thSQLTask, SqlStatementSourceType.FileConnection);

thSQLTask.FailPackageOnFailure = true;



// Add Data Flow Tasks. Create a separate task for each table.

// Get a list of tables from the source folder

arFiles = Directory.GetFileSystemEntries(sLPFDataFolder, "*.DBF");

for (iCount = 0; iCount <= arFiles.GetUpperBound(0); iCount++)

{


// Get the name of the file from the array

sDataFile = Path.GetFileName(arFiles[iCount].ToString());

sDataFile = sDataFile.Substring(0, sDataFile.Length - 4);

oDataFlow = ((TaskHost)oPackage.Executables.Add("DTS.Pipeline.1")).InnerObject as MainPipe;

oDataFlow.AutoGenerateIDForNewObjects = true;



// Create the source component

IDTSComponentMetaData90 oSource = oDataFlow.ComponentMetaDataCollection.New();

oSource.Name = (sDataFile + "Src");

oSource.ComponentClassID = "DTSAdapter.OLEDBSource.1";

// Get the design time instance of the component and initialize the component

CManagedComponentWrapper srcDesignTime = oSource.Instantiate();

srcDesignTime.ProvideComponentProperties();

// Add the connection manager

if (oSource.RuntimeConnectionCollection.Count > 0)

{


oSource.RuntimeConnectionCollection[0].ConnectionManagerID = oFoxConn.ID;

oSource.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(oFoxConn);

}

// Set Custom Properties

srcDesignTime.SetComponentProperty("AccessMode", 0);

srcDesignTime.SetComponentProperty("AlwaysUseDefaultCodePage", true);

srcDesignTime.SetComponentProperty("OpenRowset", sDataFile);

// Re-initialize metadata

srcDesignTime.AcquireConnections(null);

srcDesignTime.ReinitializeMetaData();

srcDesignTime.ReleaseConnections();

// Create Destination component

IDTSComponentMetaData90 oDestination = oDataFlow.ComponentMetaDataCollection.New();

oDestination.Name = (sDataFile + "Dest");

oDestination.ComponentClassID = "DTSAdapter.OLEDBDestination.1";

// Get the design time instance of the component and initialize the component

CManagedComponentWrapper destDesignTime = oDestination.Instantiate();

destDesignTime.ProvideComponentProperties();

// Add the connection manager

if (oDestination.RuntimeConnectionCollection.Count > 0)

{


oDestination.RuntimeConnectionCollection[0].ConnectionManagerID = oSQLConn.ID;

oDestination.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(oSQLConn);

}

// Set custom properties

destDesignTime.SetComponentProperty("AccessMode", 2);

destDesignTime.SetComponentProperty("AlwaysUseDefaultCodePage", false);

destDesignTime.SetComponentProperty("OpenRowset", "[dbo].[" + sDataFile + "]");



// Create the path to link the source and destination components of the dataflow

IDTSPath90 dfPath = oDataFlow.PathCollection.New();

dfPath.AttachPathAndPropagateNotifications(oSource.OutputCollection[0], oDestination.InputCollection[0]);

// Iterate through the inputs of the component.

foreach (IDTSInput90 input in oDestination.InputCollection)

{


// Get the virtual input column collection

IDTSVirtualInput90 vInput = input.GetVirtualInput();

// Iterate through the column collection

foreach (IDTSVirtualInputColumn90 vColumn in vInput.VirtualInputColumnCollection)

{


// Call the SetUsageType method of the design time instance of the component.

destDesignTime.SetUsageType(input.ID, vInput, vColumn.LineageID, DTSUsageType.UT_READWRITE);

}

//Map external metadata to the inputcolumn

foreach (IDTSInputColumn90 inputColumn in input.InputColumnCollection)

{


IDTSExternalMetadataColumn90 externalColumn = input.ExternalMetadataColumnCollection.New();

externalColumn.Name = inputColumn.Name;

externalColumn.Precision = inputColumn.Precision;

externalColumn.Length = inputColumn.Length;

externalColumn.DataType = inputColumn.DataType;

externalColumn.Scale = inputColumn.Scale;

// Map the external column to the input column.

inputColumn.ExternalMetadataColumnID = externalColumn.ID;

}

}

}

// Add precedence constraints to the package executables

PrecedenceConstraint pcTasks = oPackage.PrecedenceConstraints.Add((Executable)thSQLTask, oPackage.Executables[0]);

pcTasks.Value = DTSExecResult.Success;

for (iCount = 1; iCount <= (oPackage.Executables.Count - 1); iCount++)

{


pcTasks = oPackage.PrecedenceConstraints.Add(oPackage.Executables[iCount - 1], oPackage.Executables[iCount]);

pcTasks.Value = DTSExecResult.Success;

}

// Validate the package

DTSExecResult eResult = oPackage.Validate(oPkgConns, null, null, null);

// Check if the package was successfully executed

if (eResult.Equals(DTSExecResult.Canceled) || eResult.Equals(DTSExecResult.Failure))

{


string sErrorMessage = "";

foreach (DtsError pkgError in oPackage.Errors)

{


sErrorMessage = sErrorMessage + "Description: " + pkgError.Description + "";

sErrorMessage = sErrorMessage + "HelpContext: " + pkgError.HelpContext + "";

sErrorMessage = sErrorMessage + "HelpFile: " + pkgError.HelpFile + "";

sErrorMessage = sErrorMessage + "IDOfInterfaceWithError: " + pkgError.IDOfInterfaceWithError + "";

sErrorMessage = sErrorMessage + "Source: " + pkgError.Source + "";

sErrorMessage = sErrorMessage + "Subcomponent: " + pkgError.SubComponent + "";

sErrorMessage = sErrorMessage + "Timestamp: " + pkgError.TimeStamp + "";

sErrorMessage = sErrorMessage + "ErrorCode: " + pkgError.ErrorCode;

}

MessageBox.Show("The DTS package was not built successfully because of the following error(s):" + sErrorMessage, "Package Builder", MessageBoxButtons.OK, MessageBoxIcon.Information);

return false;

}

// return a successful result

return true;
}

View 2 Replies View Related

Help With Datareader

Jun 8, 2007

Hey guys, whats an easy way to pass a value into a stored procodure?
 I tried the code below but I keep on getting a "Procedure 'sp_InsertData' expects parameter '@gpiBatchNo', which was not supplied." error. My stored proc basically gets inserts the passed variable into a databaseSqlConnection sqlSecConnection = new SqlConnection(sqlPriConnString);SqlCommand sqlSecCommand = new SqlCommand();
sqlSecCommand.Connection = sqlSecConnection;
sqlSecCommand.CommandText = "sp_InsertData";sqlSecCommand.CommandType = CommandType.StoredProcedure;sqlSecCommand.Parameters.Add("@gpiBatchNo", SqlDbType.NVarChar) ;
sqlSecConnection.Open();int returntype = sqlSecCommand.ExecuteNonQuery();
sqlSecConnection.Close();

View 2 Replies View Related

How Can I Use Datareader

Oct 20, 2007

This code is currently loading my DataGridView
How can i change this to use the Datareader


Dim myConnection As SqlConnection = New SqlConnection("Data Source=ANTEC30SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Pooling=False")


Dim myCmd As SqlCommand = myConnection.CreateCommand()

myConnection.Open()


myCmd.CommandType = Data.CommandType.Text

myCmd.CommandText = "Select * From tblParts"


Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter(myCmd)

Dim myDataSet As DataSet = New DataSet()

myDataAdapter.Fill(myDataSet)


DataGridView1.DataSource = myDataSet.Tables(0)

View 7 Replies View Related

DataReader Access

Feb 22, 2007

Hi,
I am facing a problem to access datareader... actually i want to get data on lables from datareader. actually i am having one table having only one column and i hav accessed all data into datareader but the problem is that i just want to get data row by row...
 
For example there are four labels Label1, Label2, Label3, Label4
and want to print the data from datareader on to thease labels....
 
 
plz do reply... i am in trouble

View 1 Replies View Related

DataReader And DataAdapter

Feb 28, 2007

Hi,    What is the difference b/w sqldatareader and sqldataadapter? For what purpose are they used in a database connection & how do they differ from each other? Pls explain me in detail.Regards Vijay.

View 1 Replies View Related

Dataset Or Datareader?

Jun 20, 2007

i need help to know what is the best practice
i have a stored proc which returns 4 different resultselts
will that be easy to use dataset or datareader?
my purpose of using dataset/datareader is to load the data in a class
thanks.
 

View 5 Replies View Related

Datareader Problem

Aug 20, 2007

Hi,
I cant seem to get this working right...I have a datareader which i loop through...i want to test each value to see if its null but i cant get the syntax right.  
I know i use dr.item("columnname") or dr(0) to pick a certain column but i dont know the column names and want to check them all anyway.  What is the syntax to do this.
Thanks for any help...this is prob very simple but just cant see it.
--------------------------------------------While dr.Read
If dr(0) Is System.DBNull.Value Then
Return "test"End If
End While

View 3 Replies View Related

Problem With Datareader

Aug 25, 2007

Hello     i creae one programm, there is an two data reader and two Gridview or datagrid , and my programm have one error my programm is there  using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.SqlClient;public partial class aries : System.Web.UI.Page{    SqlConnection con;    SqlCommand cmd;    SqlDataReader dr;    SqlDataReader dr1;    SqlCommand cmd1;        protected void Page_Load(object sender, EventArgs e)    {        string str;        str = ConfigurationSettings.AppSettings["DBconnect"];        con = new SqlConnection(str);        con.Open();        cmd = new SqlCommand("select color from zodiac_color where Sno=1", con);        dr = cmd.ExecuteReader();        GridView1.DataSource = dr;        GridView1.DataBind();        cmd1=new SqlCommand("select number from zodiac_number where Sno=1",con);        dr1 = cmd.ExecuteReader();        GridView2.DataSource = dr1;        GridView2.DataBind();    }}  i want to calll two value in a same database but the table is diffrent so please help me ?The error is ::---------    There is already an open DataReader associated with this Command which must be closed first. please help me ashwani kumar 

View 2 Replies View Related

Datareader Problem

Apr 9, 2008

hi to all , check this once..this all data related to bus seats SeatNo1,SeatNo2 seats varchar in databaseSt1,St2    status(bit in database sqlserver2000) All my code is working when reader[i + 2].ToString() == "True" is remove from code ..so plz tell me solution gow to ckeck status with datareaderSqlCommand command = new SqlCommand("Select SeatNo1,SeatNo2,St1,St2 from tblSts where
BUSID='S0008'", sqlCon);

        sqlCon.Open();

 

        SqlDataReader
reader = command.ExecuteReader();

        int x =
0;

        while
(reader.Read())

        {

            for
(int i = 0; i <= reader.FieldCount - 1; i++)

            {

                x = (i + 1);

                System.Web.UI.WebControls.Label myLabel = ((System.Web.UI.WebControls.Label)(Page.FindControl(("Label"
+ x))));

                System.Web.UI.WebControls.CheckBox myCheckbox = ((System.Web.UI.WebControls.CheckBox)(Page.FindControl(("Checkbox"
+ x))));

                if
(reader[i].ToString() != "NULL"
&& reader[i + 2].ToString() == "True"))

                {

                    myLabel.Text =
reader[i].ToString();

                    myCheckbox.Checked = false;

                }

                else

                {

                    myLabel.Text =
reader[i].ToString();

                    myCheckbox.Visible = false;

                }

            }

        }

        sqlCon.Close(); 

View 8 Replies View Related

Datareader Timeout

Apr 25, 2008

 Hi
In my web site I call all the content from the database with the use of querystrings. I use datareader to call the data each time a request appears from the querystring.  Although I close all the connections I still get occasionally the following error:
Timeout expired the timeout period elapsed prior to obtaining a connection from the pool. This may have occured because all pooled connections were in use and max pool size was reached.
 
If it is not a programming error then what could it be? I use sql server 2005 and vs 2005 asp.net 2.0 .

View 6 Replies View Related

Open Datareader

May 2, 2008

"There is already an open datareader associated with this command which must be closed first." 
I have received this same error before, but I'm not sure why I'm getting it here.'Create a Connection object.
MyConnection = New SqlConnection("...............................")

'Check whether a TMPTABLE_QUERY stored procedure already exists.
MyCommand = New SqlCommand("...", MyConnection)

With MyCommand
'Set the command type that you will run.
.CommandType = CommandType.Text

'Open the connection.
.Connection.Open()

'Run the SQL statement, and then get the returned rows to the DataReader.
MyDataReader = .ExecuteReader()

'Try to create the stored procedure only if it does not exist.
If Not MyDataReader.Read() Then
.CommandText = "create procedure tmptable_query as select * from #temp_table"

MyDataReader.Close()
.ExecuteNonQuery()
Else
MyDataReader.Close()
End If

.Dispose() 'Dispose of the Command object.
MyConnection.Close() 'Close the connection.
End With
As you can see, the connection is opened and closed, and the datareader is closed.   Here's what comes next...'Create another Connection object.
ESOConnection = New SqlConnection("...")

If tx_lastname.Text <> "" Then
If (InStr(sqlwhere, "where")) Then
sqlwhere = sqlwhere & " AND lname like '" & Replace(tx_lastname.Text, "'", "''") & "%'"
Else
sqlwhere = " where lname like '" & Replace(tx_lastname.Text, "'", "''") & "%'"
End If
End If
If tx_firstname.Text <> "" Then
If (InStr(sqlwhere, "where")) Then
sqlwhere = sqlwhere & " AND fname like '" & Replace(tx_firstname.Text, "'", "''") & "%'"
Else
sqlwhere = " where fname like '" & Replace(tx_firstname.Text, "'", "''") & "%'"
End If
End If

dynamic_con = sqlwhere & " order by arr_date desc "

'create the temporary table on esosql.
CreateCommand = New SqlCommand("CREATE TABLE #TEMP_TABLE (".............", ESOConnection)

With CreateCommand
'Set the command type that you will run.
.CommandType = CommandType.Text

'Open the connection to betaserv.
ESOConnection.Open()

'Run the SQL statement.
.ExecuteNonQuery()

End With

'query our side
ESOCommand = New SqlCommand("SELECT * FROM [arrest_index]" & dynamic_con, ESOConnection)

'execute query
ESODataReader = ESOCommand.ExecuteReader()

'loop through recordset and populate temp table
While ESODataReader.Read()

MyInsert = New SqlCommand("INSERT INTO #TEMP_TABLE VALUES("......", ESOConnection)

'Set the command type that you will run.
MyInsert.CommandType = CommandType.Text

'Run the SQL statement.
MyInsert.ExecuteNonQuery()

End While

ESODataReader.Close()  'Create a DataAdapter, and then provide the name of the stored procedure.
MyDataAdapter = New SqlDataAdapter("TMPTABLE_QUERY", ESOConnection)

'Set the command type as StoredProcedure.
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure

'Create a new DataSet to hold the records and fill it with the rows returned from stored procedure.
DS = New DataSet()
MyDataAdapter.Fill(DS, "arrindex")

'Assign the recordset to the gridview and bind it.
If DS.Tables(0).Rows.Count > 0 Then
GridView1.DataSource = DS
GridView1.DataBind()
End If

'Dispose of the DataAdapter
MyDataAdapter.Dispose()

'Close server connection
ESOConnection.Close() Again, a separate connection is open and closed.I've read you can only have 1 datareader available per connection. Isn't that what I have here? The error is returned on this line: MyInsert.ExecuteNonQuery()
Help is appreciated.
 

View 3 Replies View Related

Datareader And Dataset

Nov 3, 2003

Hi

I am using a datareader to access data via a stored procedure. The reason for using the datareader is that the stored procedure is multi level depending on the variable sent to it. However I want to do two things with the data being returned.

The first is to poulate a datagrid - which I've done.
The second is to produce an Infragistic Web Graph. However according to the background reading I have done so far, I can only populate the graph from one of the following: datatable,dataview,dataset,Array or Ilist.

I don't want to make another call to the server for the same information, so how can I get the data out of a stored procedure into a dataset or dataview?

regards

Jim

View 1 Replies View Related

DataReader Not Reading

Jan 13, 2004

Why won't this dataReader read?

Dim objCon2 As New SqlConnection()
objCon2.ConnectionString = "a standard connection string"
objCon2.Open()

Dim objCommand As SqlCommand
objCommand = New SqlCommand(strSQL, objCon2)
Dim objReader As SqlDataReader
objReader = objCommand.ExecuteReader()

Label1.Text = objReader("email")

strSQL is a select command which I've checked (using SQL Query analyzer) does return data. I know the connection string is valid (and I presume if it wasn't that it'd fail on objCon2.open, which it doesn't).

So why oh why do I get this error on the last line (and yes, there is an "email" field in the contents of the reader)

System.InvalidOperationException: Invalid attempt to read when no data is present.

View 1 Replies View Related

Datareader And Arrays

Apr 22, 2004

I have data I am retrieving using a datareader...and SQLSERVER
It could return 1 row of information or perhaps 3 rows of information
I need to know how to use an array here I would guess so I can access each element in this row or rows.

HOw might I use reader.read and get it into the array

View 4 Replies View Related

Clarification On DataReader

Jan 19, 2006

I want to create a DataList that shows products, which will be on
multiple pages. I have my stored proc to show paged results, which
contains a return value for more records.
I have found examples of coding the DataReader, defining all the
parameters etc, but what about the drag and drop SqlDataSource?? You
can select the DataSource Mode to be "DataReader". I can put select
parameters in, with input and my return value. I don't know how to then
access the return value, or output value if needed, from this? My
DataList references the SqlDataSource, but I don't know how to get the
return/output value out??? This is very frustrating, cause I can't find
any info about it anywhere. Always input parameters, but no output.
This is my current SqlDataSource...

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
DataSourceMode="DataReader" ConnectionString="<%$
ConnectionStrings:Personal %>" SelectCommand="sp_PagedItems"
SelectCommandType="StoredProcedure">
        <SelectParameters>
           
<asp:QueryStringParameter Name="Page" QueryStringField="page" />
            <asp:Parameter Name="RecsPerPage" DefaultValue="10" />
           
<asp:QueryStringParameter Name="CategoryID" QueryStringField="cat"
/>
           
<asp:Parameter Name="RETURN_VALUE" Direction="ReturnValue" Size="1"
/>
        </SelectParameters>
    </asp:SqlDataSource>

If I take out the RETURN_VALUE Parameter, my results display in my data
list, but that's useless if I can't access the return value to
determine the remaining number of pages etc. Is my RETURN_VALUE
parameter wrong? How do I access that? My stored proc is shown below...

CREATE PROCEDURE sp_PagedItems
   (
    @Page int,
    @RecsPerPage int,
    @CategoryID int
   )
AS

-- We don't want to return the # of rows inserted
-- into our temporary table, so turn NOCOUNT ON
SET NOCOUNT ON


--Create a temporary table
CREATE TABLE #TempItems
(
   ID int IDENTITY,
   No varchar(100),
   Name varchar(100),
   SDescription varchar(500),
   Size varchar(10),
   ImageURL varchar(100)
)


-- Insert the rows from tblItems into the temp. table
INSERT INTO #TempItems (No, Name, SDescription, Size, ImageURL)
SELECT No, Name, SDescription, Size, ImageURL FROM Products WHERE CategoryID=@CategoryID

-- Find out the first and last record we want
DECLARE @FirstRec int, @LastRec int
SELECT @FirstRec = (@Page - 1) * @RecsPerPage
SELECT @LastRec = (@Page * @RecsPerPage + 1)

-- Now, return the set of paged records, plus, an indiciation of we
-- have more records or not!
SELECT *,
       MoreRecords =
   (
    SELECT COUNT(*)
    FROM #TempItems TI
    WHERE TI.ID >= @LastRec
   )
FROM #TempItems
WHERE ID > @FirstRec AND ID < @LastRec


-- Turn NOCOUNT back OFF
SET NOCOUNT OFF

View 3 Replies View Related

RecordCount With Datareader

Apr 22, 2006

I am very disappinted where Datareader have no RecordCount where I can get the total records it read. I guess I found a way:
 
sql = "SELECT *, ROW_NUMBER() OVER (ORDER BY id DESC) AS c FROM ACCOUNTS  ORDER BY c DESC"Dim command As SqlCommand = New SqlCommand(sql, New SqlConnection(_DBConnectionString))            command.Connection.Open()            _ReturnDataReader = command.ExecuteReader(CommandBehavior.CloseConnection)            command.Dispose()            _TotalRecord = _ReturnDataReader.GetInt64(_ReturnDataReader.GetOrdinal("c"))
Have SQL Server 2005 count for me....
 

View 1 Replies View Related

Datareader Security

Jun 15, 2007

As a beginner, I'm attempting to set up security for SQL Server But it's not working and am fairly confused at the moment.

The current problem is to do with getting SQL Security logins to work. I've added a login for a 'reader' user (no updates allowed) and have set the database user to use only the 'db_datareader' role. Yet, when I logon as that user, I can update data without a problem.

The system is a standalone PC using XP Pro with SQL Express installed.

The connection string is valid (and works, allowing access to all data) and is of the type:
"server=xxxxx;database=xxxx;Trusted_Connection=True;"

The application is written is VB.NET

I hope I'm making some simple mistake here and I'd really appreciate any thoughts ...

Many thanks

View 6 Replies View Related

DataReader.GetFloat From SQL DB

Apr 22, 2008



Hi All,
I am the following problem retrieving Float data from a Compact SQL database, it worked perfectly with 1.1 .Net CF, but since updating to 2.0 .Net CF its crashing with a "InvalidCastException" Error, have checked the DB its a Float...

// Start of code snip


cmd = conn.CreateCommand();

string cmdString ="select " +

RECORDNUMBER_COLUMN + ", "

+ FULLNAME_COLUMN + ", "

+ FPFILENAME_COLUMN + ", "

+ IMAGENAME_COLUMN + ", "

+ BMPNAME_COLUMN + ", "

+ TEMPLATENAME_COLUMN + ", "

+ SCORE_SCORE_COLUMN + " "

+ "from " + ENROLTABLE_NAME + " where " + RECORDNUMBER_COLUMN + " = " + iNumber;

cmd.CommandText = cmdString;

SqlCeDataReader DataReader = cmd.ExecuteReader(System.Data.CommandBehavior.SingleResult);

while(DataReader.Read())

{


recordnumber = DataReader.GetInt32(DS_WORD_COLUMNINDEX_RECORDNUMBER);

fullname = DataReader.GetString(DS_WORD_COLUMNINDEX_FULLNAME);

fpdataname = DataReader.GetString(DS_WORD_COLUMNINDEX_FPFILENAME);

fpimagename = DataReader.GetString(DS_WORD_COLUMNINDEX_IMAGENAME);

personbmpname = DataReader.GetString(DS_WORD_COLUMNINDEX_BMPNAME);

persontemplatename = DataReader.GetString(DS_WORD_COLUMNINDEX_TEMPLATENAME);
//*******************************************************


Score_Score = DataReader.GetFloat(DS_WORD_SCORE_COLUMNINDEX_TEMPLATESCORE);
// This generates the error : "InvalidCastException"
//*******************************************************


ReturnValue=true;

}

DataReader.Close();

conn.Dispose();

cmd.Dispose();



// End Of Snip


Cheers for any help with this

Adz

View 1 Replies View Related

DataReader And Bad Dates

Aug 9, 2006

Hello,

I am using a DataReader to read an ODBC Data Source.



Some of my dates are not valid. I would like to have the DataReader just treat the bad dates as Null. However I cannot seem to find a setting that will get me past the DataReader.



In SQL 2000 DTS I was able to use a script to skip the bad dates.



Please help because I don't want to have to run SQL 2000 DTS on SQL 2005.



Thanks,



Michael

View 2 Replies View Related

Datareader Does Not Return Result

Feb 23, 2007

the following is the code,....When i run this code I get "Invalid operation exception", Trying to read when no data is present, but the query returns result in query analyser...can anyone suggest what the problem is ...
Connection is open and the query is simple select statement
 
SqlCommand myCommand = new SqlCommand(query,myConnection);
myConnection.Open();
 
SqlDataReader myReader = myCommand.ExecuteReader();
 
Thanks
Niranch

View 7 Replies View Related

About Datareader And Dataset Combine Use

Dec 26, 2007

i have 2 database queries. One fetches data from a table and other according to first query result second query fetches record from another table both of these queries make use of datareader and while loop for inserting data to dropdownlist , but instead of that i want to add all my row fetched by second query store one by one in a dataset for some time .in simple words i want to insert datareader record one by one in dataset. i am using asp.net2.0,c#, Sql server 2000 

View 2 Replies View Related

How To Add Datareader Results To A Label

Feb 21, 2008

hi,
i have this code it gets the records from db
i need to add the results of the datareader to a label but label control does not have a datasource property
second problem is how to comma separate the results.with array? or what please help
i need to show the results like this: record1,record2,record3Dim Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Conn").ConnectionString)
Dim strSQL As StringDim dr As SqlDataReader
Dim userID As Integer = Session("cmmLogonUserID")
strSQL = "select id,extension from musicExt"Dim cmd As New SqlCommand()cmd = New SqlCommand(strSQL, Conn)
Conn.Open()
dr = cmd.ExecuteReader()
 
'txtMediaFormats.Text = dr ???????
' ddlGenres.DataBind() ????????
Conn.Close()

View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved