Problem With The SQL Insert With .CommandText() And .ExecuteNonQuery()
Jan 18, 2007
Hi
I have done a SQL statement INSERT for my coding. The program compiled and run the insertion with no error occurred. But after the compilation I found out that my database is not populated at all.
I tried the data insertion using the manual query, and I work perfectly.
So the problem now is that I do not know why my codes did not insert the data into my database. Will like to get some advise. Thanks
My codes are pasted in http://www.pastebin.ca/320102
The Debug.Writeline in the code is in http://www.pastebin.ca/320108
Hi , Iam new to vs2005. Iam trying to integrate Authorize.net for transactions in my site. When i tested it worked fine .But when i put it in live for Amex cards it is giving me sqlerror. Here is my code 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; using System.Net; using System.IO; public partial class Paymentprocessing : System.Web.UI.Page {SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["strConn"]); string permLevel = "";protected void Page_Load(object sender, EventArgs e) {if (Session["displayname"] == null || Session["franchiseid"] == null || Session["username"] == null) {Response.Redirect("Default.aspx"); } else {lblusrname.Text = Session["displayname"].ToString(); }string strSelectquery = ""; strSelectquery = "select userPermissionLevel,Franchise_ID from tblUsers where User_Name='" + Session["username"].ToString()+"'";SqlCommand objCmd = new SqlCommand(strSelectquery, objConn);SqlDataReader objDr; objConn.Open(); objDr = objCmd.ExecuteReader(); if (objDr.Read()) { permLevel = objDr[0].ToString(); } objDr.Close(); objConn.Close();if (int.Parse(permLevel) == 99) {pnlRefundCC.Visible = true; pnlRefundCA.Visible = true;pnlTransact.Visible = true; pnlPaymentInfo.Visible = true;pnlCardifo.Visible = true; } else {pnlPaymentInfo.Visible = true; pnlCardifo.Visible = true;pnlRefundCC.Visible = false; pnlRefundCA.Visible = false;pnlTransact.Visible = false; } }protected void RadioButton3_CheckedChanged(object sender, EventArgs e) {pnlTransact.Visible = false; pnlPaymentCCA.Visible = false;pnlOrgTransID.Visible = true;pnlCardifo.Visible = true;
Here is the error iam getting server Error in '/' Application. ----------------ExecuteNonQuery: CommandText property has not been initialized 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.InvalidOperationException: ExecuteNonQuery: CommandText property has not been initializedSource Error: Line 431: SqlCommand cmd1 = new SqlCommand(strInsert,objConn);Line 432: objConn.Open();Line 433: cmd1.ExecuteNonQuery();Line 434: objConn.Close();Line 435: Source File: d:Websitesserviceinfo.comsecurePaymentprocessing.aspx.cs Line: 433 Stack Trace: [InvalidOperationException: ExecuteNonQuery: CommandText property hasnot been initialized] System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +873524 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +72 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135 Paymentprocessing.btnSubmit_Click(Object sender, EventArgs e) in d:Websitesxyassss.aspx.cs:433 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102 ----------------Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
I keep trying to insert a Value in a field called Category and DateTIme in a field called date but I keep getting this error The datetime field in the database is a data type DateTime. I converted the varible into a ToString, I put it in a Convert.In32() method, I even set the varible to a DateTime datatype. doesnt work. whats wrong ? Server Error in '/WebSite1' Application.
Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1502: The best overloaded method match for 'System.Data.SqlClient.SqlParameterCollection.AddWithValue(string, object)' has some invalid argumentsSource Error:
Line 33: cmd.Parameters.AddWithValue("@Category", NewCat.Text); Line 34: DateTime Date = DateTime.Now; Line 35: cmd.Parameters.AddWithValue("@Date",Date.ToString); Line 36: Line 37: trySource File: c:Documents and SettingsCompaq_OwnerMy DocumentsVisual Studio 2008WebSitesWebSite1AdminCat.aspx.cs Line: 35 Show Detailed Compiler Output:
Dim MiSQL As String = "INSERT INTO tabla1(ID,Proveedor,Tipo) VALUES (@IDCentro,@Proveedor,@Tipo)" ................ cm.Parameters.Add(New SqlParameter("@IDCentro", SqlDbType.Int, 4)).Value = 15 cm.Parameters.Add(New SqlParameter("@Proveedor", SqlDbType.NVarChar, 50)).Value = "IBM" cm.Parameters.Add(New SqlParameter("@Tipo", SqlDbType.TinyInt, 1)).Value = 35Hi friens, its possible to get the string with the vaules of parameters changed?, i mean get this string in code:INSERT INTO tabla1(ID,Proveedor,Tipo) VALUES (15,IBM,35);I tried with CommandText but in this string are the variables and not the values....thx a lot.
PRAdapter.SelectCommand.CommandText = "SELECT * FROM dbo.Customer WHERE Cname = 'بهمن' ";PRAdapter.Fill(table); The table in the DataBase has a complete row contains this column. But count of rows of the table in C# is 0 (zero). I don't know why. Thanks for your answer!
Strangest thing is happening...Im building a select query..when I execute the query I get the results I want...But then I add the following code (yes am assigning the cmdText to myCommand etc, that all works):cmdText += "LookingForIDs LIKE '%,@LFID,%' "mycommand.Parameters.Add(New SqlParameter("@LFID", s(i)))(I used the debugger and this code is executed)the s() is an array of String.Now..I would expect that the @LFID part is replaced with the value of s(i)..in this case it's "2"Now when I execute the query...no results are found anymore....BUT when I execute the query in MS SQL Management Studio and replaced the @LFID manually with "2" it DOES work...and returns the right resultsAlso when I replaced the @LFID in the code with 2 so that it becomes:cmdText += "LookingForIDs LIKE '%,2,%' " it works....So my best guess is that for SOME reason the @LFID doesnt get replaced
I'm having a ton of trouble with a dataset. It builds at design time,but fails at runtime, saying:---------------------------Processing Errors---------------------------An error has occurred during report processing.Cannot set the command text for data set 'ds_Legal_Entity'.Error during processing of the CommandText expression of dataset'ds_Legal_Entity'.---------------------------OK---------------------------Below is the CommandText for ds_Legal_Entity that gives me the error:="SELECT DISTINCT dbo.t_d_legal_entity.legal_entity_desc FROMdbo.t_d_legal_entity INNER JOIN dbo.t_f_month_summary ONdbo.t_d_legal_entity.legal_entity_key =dbo.t_f_month_summary.legal_entity_key WHERE(dbo.t_f_month_summary.acctg_mth_key = " &Parameters!acctg_mth_key.Value & ")" &IIF(Parameters!BusUnitKey.Value = 0,""," AND(dbo.t_f_month_summary.bus_unit_key = " & Parameters!BusUnitKey.Value &")") & " ORDER BY dbo.t_d_business_unit.legal_entity_desc"If I delete everything after " & Parameters!acctg_mth_key.Value & ")",I won't get the error, so I assume that's where the problem lies. Ijust need another pair of eyes to see it.Thanks!Mike
Cannot set the command text for data set 'ScoreboardOLAP'.
Error during processing of the CommandText expression of dataset €˜ScoreboardOLAP€™
Can anyone help at all here? I've seen about 10 articles on this one but none appear to be relevant. I have a complex report comprising many sub-reports which runs successfully in a development environment. When deployed to an environment which comprises a separate report sever and report server DB I get the above error even when I try and browse to any of the sub-reports.
The sub-report is using an OLEDB connection to an SSAS DB and its command text is set as:-
=Code.GetQueryString(parameters)
Where GetQueryString is a function in the code section of the report which returns some MDX based on the supplied parameters. I obviously know the function works because it works in development mode.
I have tried to determine what is going on from the logs but the only messages I get are those above. I've set the data sources on the server up to use valid Windows Credentials stored on the server so I don't believe the issue is one of authentication
Any thoughts or tips in helping to diagnose the cause of the problem would be greatly appreciated.
Dear; I got a problem executenonquery in asp.net 2.0. Below as my Code: 1 Dim conn As New SqlConnection(tmpconn)2 Dim cmd1 As New SqlCommand("SP_RPTFABTRANSFER_DYEING_PREV", conn)3 4 cmd1.CommandType = CommandType.StoredProcedure5 cmd1.CommandTimeout = 9006 cmd1.Parameters.Add(New SqlParameter("@aSTDATE", SqlDbType.VarChar, 10))7 cmd1.Parameters.Add(New SqlParameter("@aEDDATE", SqlDbType.VarChar, 10))8 cmd1.Parameters.Add(New SqlParameter("@aBUYERID", SqlDbType.VarChar, 10)) 9 cmd1.Parameters.Add(New SqlParameter("@aFACTORYID", SqlDbType.VarChar, 10))10 cmd1.Parameters.Add(New SqlParameter("@aFabGrpId", SqlDbType.VarChar, 10))11 cmd1.Parameters.Add(New SqlParameter("@aFABSUPPIDFROM", SqlDbType.VarChar, 10))12 cmd1.Parameters.Add(New SqlParameter("@aFABSUPPIDTO", SqlDbType.VarChar, 10))13 cmd1.Parameters.Add(New SqlParameter("@aUSERID", SqlDbType.VarChar, 20))14 cmd1.Parameters.Add(New SqlParameter("@aDelType", SqlDbType.VarChar, 20))15 16 cmd1.Parameters("@aSTDATE").Value = lstartdt17 cmd1.Parameters("@aEDDATE").Value = lenddt18 cmd1.Parameters("@aBUYERID").Value = Trim(dropBuyer.SelectedValue)19 cmd1.Parameters("@aFACTORYID").Value = Trim(dropFactory.SelectedValue)20 cmd1.Parameters("@aFabGrpId").Value = lFabGrp21 cmd1.Parameters("@aFABSUPPIDFROM").Value = fabFrom22 cmd1.Parameters("@aFABSUPPIDTO").Value = fabTo23 cmd1.Parameters("@aUSERID").Value = Session("UID").ToString24 cmd1.Parameters("@aDelType").Value = lDelType25 Try26 conn.Open()27 cmd1.ExecuteNonQuery()28 conn.Close()29 Catch ex As Exception30 lblerr.Visible = True31 lblerr.Text = ex.Message32 Finally33 conn.Close()34 End Try Web.Config<add name="oldtextileConnectionString" connectionString="Data Source=xx.xx.xx.xx;Initial Catalog=ERP;Integrated Security=TRUE;Connection Lifetime=0;Min Pool Size =0;Max Pool Size=1000;Pooling=true;" providerName="System.Data.SqlClient"/> This Code running on asp only 2min Execute time. But i try it on Asp.net 2.0 take a long time about 15min or request time out error. Could any one can give me some tips or hits? Help much appreciated. Thanks
I hope you would help me in this problem. I use the code below for executenonquery command for mdb DB.But I do not know the changes I should made when Using SQL2005.-------------Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _ "Data Source=C:ASPNET20dataNorthwind.mdb" Dim dbConnection As New OleDbConnection(connectionString) dbConnection.Open() Dim commandString As String = "INSERT INTO Employees(FirstName, LastName) " & _ "Values(@FirstName, @LastName)" Dim dbCommand As New OleDbCommand(commandString, dbConnection) Dim firstNameParam As New OleDbParameter("@FirstName", OleDbType.VarChar, 10) firstNameParam.Value = txtFirstName.Text dbCommand.Parameters.Add(firstNameParam) Dim lastNameParam As New OleDbParameter("@LastName", OleDbType.VarChar, 20) LastNameParam.Value = txtLastName.Text dbCommand.Parameters.Add(LastNameParam) dbCommand.ExecuteNonQuery() dbConnection.Close()--------
Hi, I am trying to execute a nonquery as follows (look for bold):Dim connStringSQL As New SqlConnection("Data Source=...***...Trusted_Connection=False")'// Create the new OLEDB connection to Indexing ServiceDim connInd As New System.Data.OleDb.OleDbConnection(connStringInd)Dim commandInd As New System.Data.OleDb.OleDbDataAdapter(strQueryCombined, connInd)Dim commandSQL As New SqlCommand("GetAssetList2", connStringSQL)commandSQL.CommandType = Data.CommandType.StoredProcedureDim resultDS As New Data.DataSet()Dim resultDA As New SqlDataAdapter()'// Fill the dataset with valuescommandInd.Fill(resultDS)'// Get the XML values of the dataset to send to SQL server and run a new query...'// Return the number of resultsresultCount.Text = source.Count.ToStringresults.DataSource = sourceresults.DataBind()'// Record the searchcommandSQL = New SqlCommand("RecordSearch", connStringSQL)commandSQL.Parameters.Clear()commandSQL.Parameters.Add("@userName", Data.SqlDbType.VarChar, 50).Value = authUser.Text()commandSQL.Parameters.Add("@createdDateTime", Data.SqlDbType.DateTime).Value = DateTime.Now()commandSQL.Parameters.Add("@numRows", Data.SqlDbType.Int, 1000).Value = resultCount.TextcommandSQL.Parameters.Add("@searchString", Data.SqlDbType.VarChar, 1000).Value = searchText.TextconnStringSQL.Open()commandSQL.ExecuteNonQuery()connStringSQL.Close() The stored procedure looks like this:Use GTGAssetsDROP PROC dbo.RecordSearch;--New ProcedureGOCREATE PROC dbo.RecordSearch(@userName varchar(50),@createdDateTime DateTime,@numRows varchar(1000),@searchString varchar(1000))ASBEGINSET NOCOUNT ONINSERT INTO SearchLog (SearchString, CreatedByUser, CreatedDTTM, RowsReturned) VALUES (@searchString, @userName, @createdDateTime, @numRows)ENDGOAny ideas as to why this error is appearing? Incorrect syntax near 'RecordSearch'. 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.Data.SqlClient.SqlException: Incorrect syntax near 'RecordSearch'.Source Error: Line 169: commandSQL.Parameters.Add("@searchString", Data.SqlDbType.VarChar, 1000).Value = searchText.Text Line 170: connStringSQL.Open() Line 171: commandSQL.ExecuteNonQuery() Line 172: connStringSQL.Close() Line 173: End IfMany thanks!James
When I try to insert a record with the ExecuteNonQuery command, I get the following error information. Any clues why? Thanks. SSqlException was unhandled by user code...Message="Incorrect syntax near [output of one of my field names]."...[Item detail:] In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user. My code: Private objCmd As SqlCommandPrivate strConn As New SqlConnection(ConfigurationManager.AppSettings("conn"))...objCmd = New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _"VALUES('" & strUser & "','" & strFName.Text & "','" & strLName.Text & "', '" & strLang.Text & "', '" & strCtry.Text & "', '" & strPhone.Text & "'" _, strConn)strConn.Open()objCmd.ExecuteNonQuery()
Hi,I am developing a small application where in I need to take a few data from the user and put it on the DB. I have stored procs for the same. I am getting an error when I execute the ExecuteNonQuery() command. the error is as follows: System.InvalidCastException: Object must implement IConvertible. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Intranet_New.leaveForm.btnSubmit_Click(Object sender, EventArgs e) in c:inetpubwwwrootintranet_newleaveform.aspx.cs:line 138 Snippet of code: try { con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["SqlCon"]); cmd = new SqlCommand(); cmd.Connection = con;
( @empid as char(20), @empName as nvarchar(50), @totalLeave as decimal(9) = 12, @LeaveFrom as datetime, @LeaveTo as datetime, @TotalDays as bigint, @TypeOfLeave as nvarchar(50), @ReasonOfLeave as nvarchar(1000), @RemainigLeave as decimal(9) ) /* ( @parameter1 datatype = default value, @parameter2 datatype OUTPUT ) */ AS /* SET NOCOUNT ON */
I have created a stored procedure that takes several parameters and ultimately does an INSERT on two tables. The sp returns with an integer indicating which is positive if one or more rows were added. If I execute the SP by hand using the SQL Server Management Studio Express I get the proper results, the records are added to both tables and the return values are proper. One is an output parameter indicating the Identity value of the main record, the return value simply >0 if OK. However, when I use C#, build my connection, command and its associated parameters making sure they match the SP then I get a malfunction. The problem is that when I call ExecuteNonQuery the integer value it returns is -1 even though calling it from Mgmt. Studio gives a >0 result. Even though it returns -1 I can confirm that the records were added to BOTH tables and that the output parameter (The identity) given to me is also correct. However the return value is always -1. I have no idea what is going wrong, Since I have SQL Express 2005 I do cannot do profiling :(. I really don't see why this goes wrong and I think using ExecuteScalar is not the best choice for this type of action.
HI I am using ExecuteNonQuery to run an UPDATE statement but i keep getting the following error message: "ExecuteNonQuery: Connection property has not been initialized. " this is my code can anyone see what is wrong?
DBCommand.CommandType = CommandType.TextDBCommand.CommandText = queryCourse DBConnection.Open() ExecuteNonQuery = DBCommand.ExecuteNonQuery() DBCommand.ExecuteNonQuery() DBConnection.Close() help would be appreciated.
I have a DataAccess that has "cmd.ExecuteNonQuery" and another file SqlTableProfileProvider for a SandBox project(from ASP.NET) for a Custom TableProfileProvider. That also has a cmd.ExecuteNonQuery even thou these are 2 different files i get an error after debug.
Question is are they conflicting ? if so how can i fix this.
Code Snippets for both provided below the 2nd cmd.ExecuteNonQuery that is producing the Error is Commented in Orange...Thxs for the help Rattlerr
Incorrect syntax near ','.
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.Data.SqlClient.SqlException: Incorrect syntax near ','.
Source Error:
Line 454: cmd.CommandType = CommandType.Text; Line 455: Line 456: cmd.ExecuteNonQuery(); Line 457: Line 458: // Need to close reader before we try to update
I have an interesting error that shows up on Windows Mobile 6.0 devices but does not appear to affect Windows Mobile 5.0 devices. The application runs in .NET CF 2.0 on SQL CE 3.0 using Merge Replication. When the application starts, there is an ExecuteNonQuery prior to calling the first synchronization. It appears that once the application has replicated that you can no longer create a connection to the database and run an ExecuteNonQuery successfully. If you have already created the SqlCeConnection and just open and close it as needed that you are able to run ExecuteNonQuery commands.
In Windows Monile 6.0; however, I eventually run out of memory, like there is a leak someplace. Does anyone have any ideas for how you would actually be able to dispose of the SqlCeConnection and recreate it each time? Does calling .Close() release all the native resources on a SqlCeConnection? I am trying out one more modification, I realized the SqlCeReplication object was not being disposed of and I'm guessing this probably also uses native resources; can anyone confirm this would also potentially cause a problem?
The application works but it is aggravating to have to softboot once in awhile to recover the memory, I'd like to move beyond it. Any ideas would be great!
System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'VSReferenceNumber'. at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ASP.workingdatagrid2_aspx.myDataGrid_Update(Object Sender, DataGridCommandEventArgs e) in C:Inetpubwwwrootuapworkingdatagrid2.aspx:line 64
Here's the code::
<script runat="server">
//public string ConnString = "server=atw_data01;database=UAP;uid=atw_cheryl.theobald;pwd=nudibranch;"; public string ConnString = "Server=(local); user id=sa;password=;initial catalog = UAP;"; void BindData() { //-- Using the Try statement, we attempt to connect to our //-- database, execute a SqlDataAdapter to store our data, //-- populate a dataset and then bind that dataset //-- to our DataGrid. try { SqlConnection SqlConn = new SqlConnection(ConnString); string SqlString = "SELECT [uapID], [DealershipName], [AutoExchangeClientID], [VSReferenceNumber] FROM uapForm"; SqlDataAdapter SqlComm = new SqlDataAdapter(SqlString, SqlConn); DataSet customerData = new DataSet(); SqlComm.Fill(customerData, "uapForm");
//-- If we are not able to connect, display a friendly error catch (Exception e) { ErrorLabel.Text = "Not able to connect to database. See description below: <P>"; ErrorLabel.Text += e.ToString(); }
}
void myDataGrid_Update (object Sender, DataGridCommandEventArgs e) { //-- Take the data from each textbox in our editable item //-- and assign that text to a string variable string uapID = Convert.ToString(e.Item.Cells[0].Text); string DealershipName = ((TextBox) e.Item.Cells[1].Controls[0]).Text; string AutoExchangeClientID = ((TextBox) e.Item.Cells[2].Controls[0]).Text; string VSReferenceNumber = ((TextBox) e.Item.Cells[3].Controls[0]).Text;
//-- Again, using the Try statement, attempt to connect to our database //-- and make an update with the data from our datagrid SqlConnection SqlConn = new SqlConnection(ConnString); try { SqlConn.Open(); string SqlString = "UPDATE uapForm "; SqlString += "SET DealershipName = '" + DealershipName.Replace("'", "''") + "', "; SqlString += "AutoExchangeClientID = '" + AutoExchangeClientID.Replace("'", "''") + "' "; SqlString += "VSReferenceNumber = '" + VSReferenceNumber.Replace("'", "''") + "', "; SqlString += " WHERE uapID = '" + uapID + "'"; SqlCommand SqlComm = new SqlCommand(SqlString, SqlConn); SqlComm.ExecuteNonQuery(); SqlConn.Close(); SqlComm.Dispose(); SqlConn.Dispose(); }
//-- If for some reason we cannot connect, display a friendly error. catch (Exception exc) { ErrorLabel.Text = "Not able to connect to database. <br>Please See description below:<P> <P>"; ErrorLabel.Text += exc.ToString(); }
void myDataGrid_Edit(object Sender, DataGridCommandEventArgs e) { //-- Set the edit focus to the item that was selected myDataGrid.EditItemIndex = (int) e.Item.ItemIndex; //-- Rebind our datagrid BindData(); }
void Page_Load (object Sender, EventArgs e) { //-- If the page is not posting back, bind our datagrid if (!Page.IsPostBack) { BindData(); } }
Hi, I'm using .net 2.0 and I have created a stored procedure (sql server DB) which has one insert statement with 2 input parameters. When I execute this stored procedure using ExecuteNonQuery(), it always returning -1. I want to know how many records are effected. I want to know if there is any error. Help appreciated.
I was trying an RDA Demo project. However, everytime I pull the data from Sql Server 2005 and then move on to add a row to the table using SqlCeCommand.ExecuteNonQuery(), the application fails catastrophically without giving any exception and simply exits!
When I have pulled the data once and this application has shut down (exited) I can open it again and then continue normally but I can't expect the application to PULL the data and then even add or update a row to that table. I can do select queries fine. Why would this happen?
I am disposing all the objects that I use in both the scenarios, or atleast I believe so. Does any one have any idea?
Hy, again! I am at the begining of an application. I have some modules that insert, delete and update only one row at one table. My question is should I use dataadapter.Update() or ExecuteNonQuery(). I prefer ExecuteNonQuery because I want to build a class : DataLayer to implement my own InsertProcedure(), UpdateProcedure(),DeleteProcedure(). I want speed in my application, so which is the best: dataadapter.Update() OR ExecuteNonQuery(). Thank you!
I'm using VB.Net 2008 with SQL Compact 3.5. After trying forever, I finally got my app to open a retrieve a record from a table. Now, when I try to update the record, I get an error on the ExecuteNonQuery statement. The error says I am "attempting to read or write protected memory". The code works perfectly with an Access database.
Hey, I have a page that inserts into a customers table in the DataBase a new customer account using this function: Public Function InsertCustomers(ByRef sessionid, ByVal email, ByVal pass, Optional ByVal fname = "", Optional ByVal lname = "", Optional ByVal company = "", Optional ByVal pobox = "", Optional ByVal add1 = "", Optional ByVal add2 = "", Optional ByVal city = "", Optional ByVal state = "", Optional ByVal postalcode = "", Optional ByVal country = 0, Optional ByVal tel = "") Dim result As New DataSet Dim tempid As Integer Dim conn As New SqlConnection(ConfigurationSettings.AppSettings("Conn")) Dim Adcust As New SqlDataAdapter Adcust.InsertCommand = New SqlCommand Adcust.SelectCommand = New SqlCommand Adcust.InsertCommand.Connection = conn Adcust.SelectCommand.Connection = conn sessionExists(email, sessionid, 1) conn.Open() If fname = "" Then Adcust.InsertCommand.CommandText = "Insert Into neelwafu.customers(email,password,sessionid) Values('" & email & "','" & pass & "','" & sessionid & "')" Else Dim strsql As String strsql = "Insert Into neelwafu.customers" strsql = strsql & "(sessionid,email,password,fname,lname,company,pobox,address,address2,city,state,postalcode,countrycode,tel) values(" strsql = strsql & "'" & sessionid & "','" & email & "','" & pass & "','" & fname & "','" & lname & "','" & company & "','" & pobox & "','" & add1 & "','" & add2 & "','" & city & "','" & state & "','" & postalcode & "', " & country & ",'" & tel & "')" Adcust.InsertCommand.CommandText = strsql End If Adcust.InsertCommand.ExecuteNonQuery() Adcust.SelectCommand.CommandText = "Select Max(id) from neelwafu.Customers" tempid = CInt(Adcust.SelectCommand.ExecuteScalar()) conn.Close() Return tempid End Function -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Now, I am getting an error: Violation of PRIMARY KEY constraint 'PK_customers_1'. Cannot insert duplicate key in object 'customers'. The statement has been terminated. --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The customers table has as a primary key the 'email'..... so plz can I know why am I getting this error ???? Thank you in advance Hiba
I am working on a web service method that will return weather or not a page url is stored in the database but the ExecuteNonQuery keeps returning -1. I was just wondering if i was doing anything wrong or why the ExecuteNonQuery method does not return a value of 1 or more indicating that the pageurl exists in the database? I have tried using the SQLDataReader as well to no effect and I have verified that SELECT statement refers to valid table and field names. Any help or pointers would be appreciated. I'm still kind of a newb when it comes to db programming. 1 <WebMethod()> _2 Public Function IsPageStored(ByVal pageurl As String) As Boolean3 If String.IsNullOrEmpty(pageurl) Then Return False4 5 Dim conn As New SqlConnection()6 conn.ConnectionString = ConfigurationManager.ConnectionStrings("dbStoredList").ConnectionString7 8 Dim cmd As String 9 cmd = "SELECT [" & Constants.SourceFieldName & "] " 10 cmd &= "FROM [" & Constants.StoredCopyTableName & "] " 11 cmd &= "WHERE ([" & Constants.SourceFieldName & "] = '@Source')" 12 Dim C As New SqlCommand(cmd, conn)13 C.Parameters.AddWithValue("@Source", New SqlTypes.SqlString(pageurl))14 C.Parameters.Item("@Source").CompareInfo = SqlTypes.SqlCompareOptions.IgnoreCase15 16 conn.Open()17 18 Dim exists As Boolean = False 19 exists = (C.ExecuteNonQuery > 0)20 21 conn.Close()22 C.Dispose()23 C = Nothing 24 conn.Dispose()25 conn = Nothing26 27 Return exists28 End Function 29
My understanding from a previous thread was that ExecuteNonQuery() could be used to display the number of rows returned. Does this also work when calling stored procedures and passing parameters? I have code (shown) that perfectly calls and returns Distinct models downloaded by Country. Yet the rowCount variable displays a -1. What should I do?Dim myCommand As New SqlClient.SqlCommand myCommand.CommandText = "ap_Select_ModelRequests_RequestDateTime" myCommand.CommandType = CommandType.StoredProcedure myCommand.Parameters.AddWithValue("@selectDate", dateEntered) myCommand.Parameters.AddWithValue("@selectCountry", CInt(selectCountry)) myCommand.Connection = con con.Open() Dim rowCount As Integer = myCommand.ExecuteNonQuery() numberParts.Text = rowCount.ToString con.Close() Thank you.
Hi all! I've been banging my head on this for way to long and decided it's time to reach out for help. I'll try to be complete and concise with this, but this will end up being lengthy most likely. The crux of the issue is that I apparently do not have any control over what is returned from a stored proc via the SqlCommand.ExecuteNonQuery method. I want the procedure to explicitly return 0 if the proc was successful, otherwise it will return the error code generated. A value of -1 is consistently being returned when SET NOCOUNT ON is in place, and when not, a 1 is returned. This seems to be ignoring the fact that I have RETURN 0 at the end of the proc. Perhaps I'm missing something, but if I RETURN 0, I should get 0...here is the procedure:1 ALTER PROCEDURE [dbo].[epsp_EditCities] 2 @CityId int = null, 3 @City varchar(50), 4 @CreatedBy int, 5 @UpdatedBy int, 6 @ActionType varchar(1) = 'X', 7 @Identity int = 0 OUT, 8 @RowCount int = 0 OUT 9 10 AS 11 DECLARE @ERROR int -- Local @@ERROR 12 13 14 SET NOCOUNT ON 15 BEGIN TRAN 16 17 IF @ActionType = 'I' /* --- INSERT --- */ 18 BEGIN 19 20 INSERT INTO [EnrollmentPrograms].[dbo].[Cities] 21 ([City] 22 ,[CreatedBy] 23 ,[UpdatedBy]) 24 VALUES 25 (@City 26 ,@CreatedBy 27 ,@UpdatedBy) 28 SET @Identity = SCOPE_IDENTITY() 29 30 END 31 32 IF @ActionType = 'U' /* --- UPDATE --- */ 33 BEGIN 34 35 UPDATE [EnrollmentPrograms].[dbo].[Cities] 36 SET [City] = @City 37 ,[UpdatedBy] = @UpdatedBy 38 WHERE CityId = @CityId 39 END 40 41 IF @ActionType = 'D' /* --- DELETE --- */ 42 BEGIN 43 44 DELETE FROM [EnrollmentPrograms].[dbo].[Cities] 45 WHERE CityId = @CityId 46 END 47 48 49 -- Error checking (place this after every statement) -- 50 SET @ERROR = @@ERROR 51 SET @RowCount = @@ROWCOUNT 52 53 IF @ERROR != 0 GOTO HANDLE_ERROR 54 55 COMMIT TRAN -- No Errors, so go ahead 56 57 RETURN 0 58 59 HANDLE_ERROR: 60 ROLLBACK TRAN 61 RETURN @ERRORAnd a fascinating tidbit is the results from this which shows the return value as 0:1 DECLARE@return_value int, 2 @Identity int--, 3 --@RowCount int 4 5 EXEC@return_value = [dbo].[epsp_EditCities] 6 @CityId = 1, 7 @City = N'Agoura Hills', 8 @CreatedBy = 1, 9 @UpdatedBy = 1, 10 @ActionType = N'U', 11 @Identity = @Identity OUTPUT--, 12 --@RowCount = @RowCount OUTPUT 13 14 SELECT@Identity as N'@Identity'--, 15 --@RowCount as N'@RowCount' 16 17 SELECTReturnValue = @return_value
And finally, here is the C# call that always returns -1: retVal = cmd.ExecuteNonQuery(); Now, I've tried almost all variations and unit tests on the procedure that I could dream up. Commenting this out and putting this in etc....I still remain unable to fix the return code to 0 and get that result into my retVal var. Any love? Much thanks in advance for spending time on my issue! Cheers! Wayne
I am trying to create a web form that will be used to create new users. The first step that I am taking is creating a web form that can check the username against a database to see if it already exists. I would it to do this on the fly, if possible. When I execute my current code, I get the following error:
ExecuteNonQuery: Connection property has not been initialized
Below is the code from the page itself: ----- <!-- #INCLUDE FILE="../include/context.inc" --> <!-- #INCLUDE FILE="../include/db_access.inc" -->
<script language="VB" runat="server">
Sub CheckButton_Click(Sender as Object, e as EventArgs)
cmd.ExecuteNonQuery() result = cmd.Parameters("result").Value
If result <> 1 Then CheckResults.Text="<font color=""#ff0000"">Username already exists!</font>" Else CheckResults.Text="<font color=""#009900"">Username is available.</font>" End If
Can anyone see why I might get this error? Here are some more details of the error:
Line 15: cmd.Parameters.Add( "@userName", OdbcType.VarChar, 100 ).Value = Request.Form("userName") Line 16: *Line 17: cmd.ExecuteNonQuery() Line 18: result = cmd.Parameters("result").Value