Datareader, DBNull And ?? Operator
Feb 5, 2006
Hi!
I was trying to use the ?? operator with an DBDatareader. eg:
long lValue = Convert.ToInt32(objReader["ParentID"] ?? -1);
which throws the following exception: "... Object cannot be cast from DBNull to other types."
I think the reason is, that DBNull.Value isn´t actually null. Therefore I changed my code to:
long lValue = objReader["ParentID"] != DBNull.Value ? Convert.ToInt32(objReader["ParentID"]) : -1;
Is there a better way of doing this ? Can one use the ?? operator with a Datareader anyway?
Thanks for your help!
PS: sorry for my poor english.
View 2 Replies
ADVERTISEMENT
May 3, 2007
As a part of migration to .net we are redesigning sql server 7 database and moving it to sql server 2005. There are a lot of fields with dbnull value in the existing db. It would be nice to populate them with some default value while transfering data to the new datbase on sql server 2005.
What is the best way to deal with the issue, are there any possible drawbacks and problems.
Your input will be greatly appreciated.
View 1 Replies
View Related
Jan 10, 2008
Hello!
Is there an easy way to deal with this situation below when reading in data from a SQL Database:
int? myNullableColumn;myNullableColumn = Convert.ToInt32(datarow["datacolumn"]);
Where, ideally, 'myNullableColumn' would be 'null' if the value was 'DBNull.Value'. This does not work because Convert.ToInt32 will not convert 'DBNull.Value to null', but instead throws an error.
Is there a built in funtion that does do this?
Thanks!
View 8 Replies
View Related
Jan 26, 2004
Hello,
If I have a database table with column that can accept null values and I want to insert a null value into that column, what is the correct syntax?
db_cmd = New SqlCommand( "sp_stored_procedure", db_connection )
db_cmd.CommandType = CommandType.StoredProcedure
db_cmd.Parameters.Add( "@col_to_set_to_null", ??? )
ie: what expression can be used for "???"
Ideally, I want to check if a string value is empty and if so insert a null, but I have yet to see any examples, ie:
if ( str.empty ) then
insert DBNull.value into column
else
insert str into column
end if
Sincerely,
Brent D.
View 1 Replies
View Related
Apr 2, 2007
Am getting errors on this syntax:
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Row.myColumn = DBNull.Value
Value of type 'System.DBNull' cannot be converted to type 'String'
Any ideas? Just want to set the myColumn to NULL.
Thanks
View 1 Replies
View Related
Mar 11, 2004
Hi
I have only been coding in .Net for about six months, and am not sure if this is a C# problem or an SQL one. I use the Data Access Application Block in my program.
I have two optional fields on my form (RangeFrom and RangeTo). If the user chooses not to enter data into these textboxes(textbox = ""), an entry on the db is created with null values. It works.
But sometimes the user wants to enter 0 as either an upper or lower end of a range. This is where my problem comes in. My program saves 0 as null too.
In my program I do a test on the textboxes and populate two float values in a business object (objQuestion) accordingly, like this:
if (txtrangefrom.Text != "") {
objQuestion.RangeFrom=float.Parse(txtrangefrom.Text);
objQuestion.RangeTo=float.Parse(txtrangeto.Text);
}
else {
objQuestion.RangeFrom=Convert.ToSingle(null);
objQuestion.RangeTo=Convert.ToSingle(null);
}
And this is what my Business object look like. It sets up the parameters and calls the Data Access Application Block to create an entry in my table:
// fieldslist
float cvintRangeFrom;
float cvintRangeTo;
//properties
public float RangeFrom {
get {
return cvintRangeFrom;
}
set {
cvintRangeFrom = value;
}
}
public float RangeTo {
get {
return cvintRangeTo;
}
set {
cvintRangeTo = value;
}
}
// some code deleted for readability....
public int AddOption() {
string cvstrSpName = "addOption";
SqlParameter [] cvstrStoredParams = SqlHelperParameterCache.GetSpParameterSet(gcstrConnectionString, cvstrSpName, true);
//lines deleted for readability...
//check if the optional fields have a value associated with them. if not, assign dbnull.value.
cvstrStoredParams[4].Value=(cvintRangeFrom != Convert.ToSingle(null) ? cvintRangeFrom : (object)DBNull.Value);
cvstrStoredParams[5].Value=(cvintRangeTo != Convert.ToSingle(null) ? cvintRangeTo : (object)DBNull.Value);
//lines deleted for readability...
SqlHelper.ExecuteNonQuery(gcstrConnectionString, CommandType.StoredProcedure, cvstrSpName, cvstrStoredParams);
return(cvintOptionID = Convert.ToInt32(cvstrStoredParams[0].Value));
}
I use Convert.ToSingle when working with nulls (or possible nulls) because I get an error when I use float.parse for this.
The thing is, after this method AddOption has been executed, I test the value if the business object's rangefrom (that is where I entered 0) and display it on my form. I still shows a 0, but on my database table it is null!
objQuestion.AddOption();
//txtrangefrom.Text=""; on the next line I test the value in the business object...
txtrangefrom.Text=objQuestion.RangeFrom.ToString(); // and this displays 0!!!
//txtrangeto.Text="";
txtrangeto.Text=objQuestion.RangeTo.ToString();
So to me it seems the problem seems to be either the DAAB or on the SQL side, but hopefully somebody can prove me wrong! I was thinking that it could also be float.parse/Convert.ToSingle methods and have done various tests, but I am none the wiser...
Any help or ideas will be greatly appreciated...
View 2 Replies
View Related
Jan 3, 2006
I haven't tested it, because at the moment I can't access my SQL database
I know this is probably a stupid question, but...How can I test for DBNull when I'm using SqlDataReader.Item(string)?
I use to check it using: if(!reader.IsDBNull(2)) ...But I have found that can not count on a particular ordinal reference because some of the stored procedures select the columns in different orders.
can I do something like: if(reader["Column1"] != DBNull.Value)or with the reader["Column1"] throw an error because it is not found??
I too hate when people ask questions that they could test themselves...but I can't really test it at the moment. Any input would be greatly appreciated.
View 2 Replies
View Related
Apr 24, 2006
Hi,
I have built a few pages and a stored procedure and a class on the back of a SQL2000 dbase. and I get the following error:
Cast from type 'DBNull' to type 'String' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Cast from type 'DBNull' to type 'String' is not valid.Source Error:
Line 111: Dim myWorkJobs As WorkJobsDATA = New WorkJobsDATA
Line 112:
Line 113: myWorkJobs.CustomerID = CStr(parameterCustomerID.Value)
Line 114: myWorkJobs.WorkID = CStr(parameterWorkID.Value)
Line 115: myWorkJobs.DateOfQuote = CStr(parameterDateOfQuote.Value).Trim()
Source File: C:InetpubwwwrootCommerceComponentsWorkJobs.vb Line: 113
My Database has 1 line of data (for testing) and all fields are populated. I am Querying a column called IndividualID which has a value of 3425243 at the moment. This is hardcoded in the aspx.vb at the moment.
ASPX VB:
Public Class WorkRequest Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here End Sub
Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click
'for now, send this value (stored in dbase under individualID) to the querystring
Dim IndividualID As String = "3425243"
Response.Redirect("WorkRequestMain.aspx?IndividualID=" & IndividualID) End SubEnd Class
COMPONENTSWorkJobs.vb (This is the class file)
Imports SystemImports System.ConfigurationImports System.DataImports System.Data.SqlClient
Namespace ASPNET.StarterKit.Commerce
Public Class WorkJobsDATA
Public CustomerID As String Public WorkID As String Public DateOfQuote As String Public QuoteAmount As String Public Title As Decimal Public FirstName As String Public Surname As String Public FirstLine As String Public District As String Public Town As String Public Postcode As String Public Telephone As String Public Requirements As String Public WorkRequired As String Public EmailAddress As String
End Class
Public Class WorkJobs
Public Function GetWorkDetails(ByVal IndividualID As String) As WorkJobsDATA
Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim myCommand As SqlCommand = New SqlCommand("SP_PendingQuotes", myConnection)
' Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure
' Add Parameters to SPROC Dim parameterIndividualID As SqlParameter = New SqlParameter("@IndividualID", SqlDbType.NVarChar, 50) parameterIndividualID.Value = IndividualID myCommand.Parameters.Add(parameterIndividualID)
Dim parameterCustomerID As SqlParameter = New SqlParameter("@CustomerID", SqlDbType.BigInt, 8) parameterCustomerID.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterCustomerID)
Dim parameterWorkID As SqlParameter = New SqlParameter("@WorkID", SqlDbType.NVarChar, 50) parameterWorkID.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterWorkID)
Dim parameterDateOfQuote As SqlParameter = New SqlParameter("@DateOfQuote", SqlDbType.DateTime, 8) parameterDateOfQuote.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterDateOfQuote)
Dim parameterQuoteAmount As SqlParameter = New SqlParameter("@QuoteAmount", SqlDbType.Money, 8) parameterQuoteAmount.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterQuoteAmount)
Dim parameterTitle As SqlParameter = New SqlParameter("@Title", SqlDbType.NVarChar, 50) parameterTitle.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterTitle)
Dim parameterFirstName As SqlParameter = New SqlParameter("@FirstName", SqlDbType.NVarChar, 50) parameterFirstName.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterFirstName)
Dim parameterSurname As SqlParameter = New SqlParameter("@Surname", SqlDbType.NVarChar, 50) parameterSurname.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterSurname)
Dim parameterFirstLine As SqlParameter = New SqlParameter("@FirstLine ", SqlDbType.NVarChar, 50) parameterFirstLine.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterFirstLine)
Dim parameterDistrict As SqlParameter = New SqlParameter("@District", SqlDbType.NVarChar, 50) parameterDistrict.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterDistrict)
Dim parameterTown As SqlParameter = New SqlParameter("@Town", SqlDbType.NVarChar, 50) parameterTown.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterTown)
Dim parameterPostcode As SqlParameter = New SqlParameter("@Postcode", SqlDbType.NVarChar, 50) parameterPostcode.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterPostcode)
Dim parameterTelephone As SqlParameter = New SqlParameter("@Telephone", SqlDbType.NVarChar, 50) parameterTelephone.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterTelephone)
Dim parameterRequirements As SqlParameter = New SqlParameter("@Requirements", SqlDbType.NVarChar, 3500) parameterRequirements.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterRequirements)
Dim parameterWorkRequired As SqlParameter = New SqlParameter("@WorkRequired", SqlDbType.NVarChar, 3500) parameterWorkRequired.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterWorkRequired)
Dim parameterEmailAddress As SqlParameter = New SqlParameter("@EmailAddress", SqlDbType.NVarChar, 100) parameterEmailAddress.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterEmailAddress)
myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close()
parameterEmailAddress.Value.GetType()
Dim myWorkJobs As WorkJobsDATA = New WorkJobsDATA
myWorkJobs.CustomerID = CStr(parameterCustomerID.Value) myWorkJobs.WorkID = CStr(parameterWorkID.Value) myWorkJobs.DateOfQuote = CStr(parameterDateOfQuote.Value).Trim() myWorkJobs.Title = CStr(parameterTitle.Value).Trim() myWorkJobs.FirstName = CStr(parameterFirstName.Value).Trim() myWorkJobs.Surname = CStr(parameterSurname.Value).Trim() myWorkJobs.FirstLine = CStr(parameterFirstLine.Value).Trim() myWorkJobs.District = CStr(parameterDistrict.Value).Trim() myWorkJobs.Town = CStr(parameterTown.Value).Trim() myWorkJobs.Postcode = CStr(parameterPostcode.Value).Trim() myWorkJobs.Telephone = CStr(parameterTelephone.Value).Trim() myWorkJobs.Requirements = CStr(parameterRequirements.Value).Trim() myWorkJobs.WorkRequired = CStr(parameterWorkRequired.Value).Trim() myWorkJobs.EmailAddress = CStr(parameterEmailAddress.Value).Trim()
Return myWorkJobs
End Function
End ClassEnd Namespace
And finally my stored procedure:
CREATE Procedure SP_PendingQuotes( @IndividualID nvarchar, @CustomerID bigint OUTPUT, @WorkID nvarchar(50) OUTPUT, @DateOfQuote datetime OUTPUT, @QuoteAmount money OUTPUT, @Title nvarchar(50) OUTPUT, @FirstName nvarchar(50) OUTPUT, @Surname nvarchar(50) OUTPUT, @FirstLine nvarchar(50) OUTPUT, @District nvarchar(50) OUTPUT, @Town nvarchar(50) OUTPUT, @Postcode nvarchar(50) OUTPUT, @Telephone nvarchar(50) OUTPUT, @Requirements nvarchar(3500) OUTPUT, @WorkRequired nvarchar(3500) OUTPUT, @EmailAddress nvarchar(100) OUTPUT)AS
SELECT @IndividualID = IndividualID, @CustomerID = CustomerID, @WorkID = WorkID, @DateOfQuote = DateOfQuote, @QuoteAmount = QuoteAmount, @Title = Title, @FirstName = FirstName, @Surname = Surname, @FirstLine = FirstLine, @District = District, @Town = Town, @Postcode = Postcode, @Telephone = Telephone, @Requirements = Requirements, @WorkRequired = WorkRequired, @EmailAddress = EmailAddress
FROM PendingQuotes
WHERE IndividualID = @IndividualIDGO
Any ideas anyone?
I appreciate this is a big amount of data, but if anyone wants to chat to me i'm available on MSN Messenger under wolvokid@msn.com
View 2 Replies
View Related
Jul 20, 2005
Dear GroupI'm having a very weird problem. Any hints are greatly appreciated.I'm returning two values from a MS SQL Server 2000 stored procedure to myASP.NET Webapplication and store them in sessions.Like This:prm4 = cmd1.CreateParameterWith prm4..ParameterName = "@Sec_ProgUser_Gen"..SqlDbType = SqlDbType.VarChar..Size = 10..Direction = ParameterDirection.OutputEnd Withprm5 = cmd1.CreateParameterWith prm5..ParameterName = "@Sec_ProgUser_Key"..SqlDbType = SqlDbType.VarChar..Size = 10..Direction = ParameterDirection.OutputEnd With....cmd1.ExecuteNonQuery()....Session("Sec_ProgUser_Gen") = prm4.ValueSession("Sec_ProgUser_Key") = prm5.ValueBoth output parameters are declared as varchar(10) within the storedprocedure. If I run the stored procedure in SQL Analyzer, I'm getting astring value for each of them. E.g. @Sec_ProgUser_Gen is "1110011",@Sec_ProgUser_Key = "1100".Now the strange thing happens if I try to run the following code:Sub MyTest()Dim MyString1 As StringDim MyString2 As StringMyString1 = CStr(Session("Sec_ProgUser_Key"))....MyString2 = CStr(Session("Sec_ProgUser_Gen"))End SubIt fails in line 'MyString2 = CStr(Session("Sec_ProgUser_Gen"))' with Castfrom type 'DBNull' to type 'String' is not valid.I don't understand this. They are both the same, the only difference is thelength of the string. Help!Additional Information:The values for @Sec_ProgUser_XXX are created in the stored procedure with astatement like this:SET @Sec_ProgUser_Key = (SELECT Convert(varchar(1),Key_CanCreateKey) +Convert(varchar(1),Key_CanCreateTransaction) +Convert(varchar(1),Key_CanView) + Convert(varchar(1),Key_CanDelete) FROMi2b_proguser_securityprofile WHERE SecurityProfileID = @SecurityProfileID)The datatype of the source columns used to be bit then changed them toInteger as I thought this might cause the problem. (Although it shouldn't asthe values get converted to varchar without a problem in the storedprocedure. No fields contain NULL values, only 1 or 0.
View 1 Replies
View Related
Jun 2, 2007
Hello,
VS 2005
I am developing the database application. This is a live database and is being used by the customer. I am to release a new version and I had to add new columns to fit the requirements DateStarted (DateTime), and TotalHours(Int) into a database table.There are already over a 1000 rows in this table.
When the customer wants to look at a record in this table and insert the value into the text boxes (Front-end), when it gets to the DateStarted or TotalHours it comes up with a error message:"
The value for column 'DateStarted' in table 'IncidentTask' is DBNull."The method for inserting is:
Code Snippet
Me.dtDateStarted.Value = Me.DsIncidentsControl.IncidentTask(0).DateStarted
What are the possible solutions to this problem? Would it mean checking for a DBNULL before displaying in the textboxes? Or updating the new column rows with an date:
Code Snippet
UPDATE IncidentTask SET DateStarted = '1/1/2005' WHERE (DateStarted IS NULL)
Many thanks for any suggestions,
Steve
View 1 Replies
View Related
May 23, 2006
How to set NULL values inside VB Script .Net?? Both causes error:
.FECHAAP = NULL
.FECHAAP = System.DBNull
View 3 Replies
View Related
Aug 21, 2007
Hi,I have a ShoppingCart class with a lot of properties (due to structure of a legacy Orders table). I have a ShoppingCart table also which contains a lot of the same fields as my orders table.There are a lot of fields (mostly ints) which have been initalised to 0
in my ShoppingCart class and then inserted into the ShoppingCart table
when users add items to the cart. These fields are then inserted into the orders table upon check out. When i attempt to place a new record in the orders table from the ShoppingCart table, I am receiving a bunch of Foregin Key constraint errors due to all the int fields containing 0's.What i would like to do is initalise all the properites of my ShoppingCart object to DBNull.Value but of course I can't convert type 'System.DBNull' to 'int' and i can't set to 'null' either as int's are value types.I also tried:private Int32 _fieldname = Convert.ToInt32(DBNull.Value);This compiled but gave InvalidCastException runtime error.So the only option that i can think of is, as i build the parameter array to be sent to my stored procedure, test the value of each parameter, if it is 0 (or an empty string) then don't pass the actual field value but pass DBNull.Value instead.I REALLY don't want to do this as there are around 60 parameters being passed to this procedure and this will be time consuming and messy.Any suggestions would be most appreciated!ps If i could avoid having 60 parameters being passed I would...trust me!
View 2 Replies
View Related
Jan 22, 2008
Hi,I have a stored procedure which returns an integer indicating whether the operation has succeeded or failed. It does this by calling set @returnvalue = (0 or 1) then select @returnvalue as returnvalue in the stored procedure code. When I run the stored procedure, inputting a set of parameters as it expects, it does what it's supposed to do and outputs a table with a single row and a single column, called returnvalue, which has a value of either 1 or 0. When I run the stored procedure through a function in asp, using the exact same set of parameters, output the results as a data set and try and convert the return as an integer I get the following error: "Object Cannot be cast from DBNull from other types"The conversion code is ..return Convert.ToInt32(ds.Tables[0].Rows[0]["returnvalue"]);And if I change "returnvalue" to anything else (like "wibble" for example) then I get a different error telling me it can't find the column named "wibble". So the dataset definitely contains a table with a column in it called returnvalue, as you expect. But it's value is, apparently, DBNull instead of an integer.How come this works when called directly through SQL and fails when called through ASP? Can anyone help? This is really doing my head in!Cheers,Matt
View 2 Replies
View Related
Mar 31, 2008
Ok well i have a stored procedure that returns an integer between 1 and 5. My problem now is i want to check to see if the table will return NULL and if so i don't want to assign the value to my variable otherwise it'll trow an error. My code is listed below but i keep getting the error "Conversion from type 'DBNull' to type 'Integer' is not valid." i've also tried If getoptionpicked.Parameters("@optionpicked").Value = Nothing ThenIf getoptionpicked.Parameters("@optionpicked").Value Is system.dbnull Then below is the rest of the code If getoptionpicked.Parameters("@optionpicked").Value Is Nothing Then Else optionpicked = getoptionpicked.Parameters("@optionpicked").Value If optionpicked = 1 Then option1.Checked = True ElseIf optionpicked = 2 Then option2.Checked = True ElseIf optionpicked = 3 Then option3.Checked = True ElseIf optionpicked = 4 Then option4.Checked = True ElseIf optionpicked = 5 Then option5.Checked = True Else End If End If
View 1 Replies
View Related
Oct 20, 2015
I want restore database in my disk , but i cant . I've click and add from device. this is the screen. And when i click content , it show me this text : Object cannot be cast from DBNull to other types. (mscorlib) .
View 2 Replies
View Related
Feb 21, 2008
I have quite a few tables which allow NULL values. I have to struggle a lot with DBnull Exceptions :|example: col1,col2,... are all columns of type Integer and possibly NULL. var query = from person in table select new { person.col1, test = (int?) person.col2, person.col3, person.col4, ...}; As soon as my result encounters a DBNull value.. the whole query fails. This is really bad.How would I return the valid values.. and set the keys where there is no value to a null type? (e.g. int -> 0)I tried using "(int?)" but I'm not *really* sure what it does :-) Anyway.. it has no effect :-)
View 1 Replies
View Related
Apr 24, 2007
I'm creating an ISP for extractig data from a text file and put it in a database.
One of the fields in my textfile contains the value '0' or a date. If it's '0' it should be converted to the Null Value. The column in which it has to be saved is of type smalldatetime.
This is the code of my script where I want to check the value of the field in my textfile and convert it to a date or to Null.
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
If Row.cdDateIn = "" Or Row.cdDateIn= "0" Then
Row.cdDateInCorr = CDate(DBNull.Value)
ElseIf Row.cdDateIn_IsNull Then
Row.cdDateInCorr = CDate(DBNull.Value)
Else
Row.cdDateInCorr = CDate(Row.cdDateIn)
End If
End Sub
The error that I get is:
Validation error. Extract FinCD: Conversion of cdDateIn [753]: Eroor 30311: Value of type 'System.DBNull' cannot ben converted to 'Date'.
How do I resolve this problem ?
View 8 Replies
View Related
Jun 2, 2004
I get this error when I attempt to read from a datareader using the following sql statement:
Dim mysql As String = "SELECT PayrollTrans.PayrollID, Employees.[EmpFirstName] & ' ' & " _
& " Employees.[emplastname] AS FullName, Employees.[City] & ', ' & Employees.[State] & ' ' & Employees.[zip] AS CityState " _
& " , PayrollTrans.Date, PayrollTrans.EmployeeID, PayrollTrans.RegHours, " _
& " PayrollTrans.OTHours , PayrollTrans.RegPay, PayrollTrans.OTPay, " _
& " PayrollTrans.FedTax, PayrollTrans.FICATax, PayrollTrans.MedicareTax, " _
& " PayrollTrans.ESCTax, PayrollTrans.StateTax, PayrollTrans.ESCEMPTax, " _
& " PayrollTrans.FUTATax, PayrollTrans.NetPay, Employees.EmployeeID, " _
& " Employees.Address1, Employees.Address2, Employees.SSAN, " _
& " Employees.PayType, Employees.RegPayRate, Employees.OTPayRate, " _
& " Employees.MaritalStatus, Employees.FedExemption, Employees.StateExemption, " _
& " Employees.Active, Employees.SelectforPay, Employees.PayDate " _
& " FROM PayrollTrans, Employees where PayrollTrans.EmployeeID = Employees.EmployeeID;"
my reader command list as follows:
Dim objCM As New SqlClient.SqlCommand(mysql, SqlConnection1)
Dim objDR As SqlClient.SqlDataReader
objDR = objCM.ExecuteReader
Any ideas on where I am going wrong?
Thanks in advance
View 3 Replies
View Related
May 18, 2004
I am getting a error message saying: Invalid operator for data type. Operator equals boolean AND, type equals datetime.
I traced the pointer to @gdo and @gd, they are both dates!
INSERT INTO AdminAlerts values (CURRENT_USER, 'UPDATE', getDate(), @biui, 'Updated booking, ID of booking updated: ' & @biui & ', Booking date and time before/after update: ' & @gdo & '/' & @gd & ', Room number before/after update: ' & @rno & '/' & @rn & ' and Customer ID before/after update: ' & @cio & '/' & @ci)
If I cut that two dates out it works fine.
Could someone tell me the syntax to include a date in a string :confused:
View 3 Replies
View Related
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
Mar 7, 2008
Hello Friends
How are you?? Friends i am getting problem in SQL Server 2005. I am deployng web application on production server as well as Databse also. In production server i inserted new field in all tables which is rowguid and its type is uniqueidentifier. The default binding for this field is newsequentialid(). In some pages it works ok but in some places it generates error like 'Conversion from type 'DBNull' to type 'String' is not valid'. Can anybody help me to solve this problem. Its urgent so plz reply me as soon as possible. I'll be very thankfull to you. Thanks in Advance.
Regards,
View 1 Replies
View Related
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
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
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
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
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
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
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
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
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
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
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
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