Re-use SqlCommand Object
Oct 19, 2006
Is it ok to re-use a SqlCommand object? In a method, I am executing 2 separate parameterized sql statements. Before I run the second, I will clear the command objects parameters.(command.parameters.clear()) I'm just checking to see if it is good coding practice or not.
thanks,
SC
View 2 Replies
ADVERTISEMENT
Sep 21, 2006
Hi,I'm new to ASP.NET, and am currently looking into XML.I'm trying to write XML using data from an SQL Server 2000 table. But I seem to be getting the following error regarding the SQL Server connection:Compiler Error Message: CS1502: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid argumentsSource Error:Line 23: {
Line 24: SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
Line 25: mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, connString);
Line 26: mySqlDataAdapter.Fill(myDataSet);
Line 27: return myDataSet;Source File: c:InetpubwwwrootmappingcreateGeoRSSFile.aspx.cs Line: 25 This is my code:using System;
using System.Data;
using System.Data.SqlClient ;
using System.Configuration;
using System.Collections;
using System.Text;
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;
public partial class createGeoRSSFile : System.Web.UI.Page
{
protected void Page_Load(object sender, DataSet myDataSet, EventArgs e)
{
string connString = "server=SQLSERV1;database=Historical_Statistics;UID=dbuser;PWD=Password";
string queryString = "SELECT Town, PostCode, Latitude, Longitude FROM UKPostCodes";
using (SqlConnection mySqlConnection = new SqlConnection(connString))
{
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, connString);
mySqlDataAdapter.Fill(myDataSet);
return myDataSet;
}
// Create a new XmlTextWriter instance
XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.Unicode);
// Start writing!
writer.WriteStartDocument();
writer.WriteStartElement("item");
// Creating the <town> element
writer.WriteStartElement("town");
writer.WriteElementString("PostCode",myDataSet .Tables[1].Columns("PostCode"));
writer.WriteElementString("geo:lat",myDataSet.Tables[1].Columns("Latitude"));
writer.WriteElementString("geo:lon", myDataSet.Tables[1].Columns("Longitude"));
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}What seems to be causing this error?Thanks.
View 4 Replies
View Related
Feb 10, 2008
Hi
Is it possible To pass an SQL command to a ASp.net web service as system.data.SQLclient.sqlcommand?
That means is ispossible to pass the actuall sql command instead of just the string?
If yes how can you do that??
Cheers
View 1 Replies
View Related
Jan 8, 2007
Hi guys. I'm having trouble declaring an sqlcommand. What I want to do is declare a global sqlcommand and I would want this sqlcommand to vary depending on the conditions on my page_load.
Here's the code....
Dim p_s_syounin2 As New SqlCommand
Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
If (Session("syozokubu_id") = 20) And (Session("syozokuka_id") = 21) And ((Session("kaikyuu_id") = 23)) Then
p_s_syounin2 = ("INSERT INTO (p_s_syounin2) SELECT syain_hnm FROM TR_syainID WHERE TR_syainID.syozokubu_id=20 AND TR_syainID.syozokuka_id=21 AND TR_syainID.kaikyuu_id=23, cnn") '''' THIS DOES NOT WORK!
End If
End Sub
p_s_syounin2 .ExecuteNonQuery()
What is the correct way of declaring p_s_syounin2?
Thanks.
Best Regards,
Audrey
View 5 Replies
View Related
Oct 11, 2006
Hi There,This is related to a ms access database but since I use the SqlDataSource control I thought I should post here.I have a project that I was working on with this ms access db and using sql controls, everything was working just finesince one day I started getting "Object reference not set to an instance of an object" messages when I try to designa query or retrieve a schema, nothing works at design time anymore but at runtime everything is perfect, its a lotof work for me now to create columns,schemas and everything manually, I've tried reinstalling visualstudio, ado componentsbut nothing seems to fix it, did this ever happen to any of you guys?any tip is really appreciated thanks a lot
View 2 Replies
View Related
Dec 17, 2007
Does any one has any clue for this error ? I did went through a lot of articles on this error but none helped . I am working in Visual studie 2005 and trying to upload image in sql database through a simple form. Here is the 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.Web.Configuration;
using System.IO;
public partial class Binary_frmUpload : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
{
}protected void btnUpload_Click(object sender, EventArgs e)
{if (FileUpload.HasFile == false)
{
// No file uploaded!lblUploadDetails.Text = "Please first select a file to upload...";
}
else
{string str1 = FileUpload.PostedFile.FileName;
string str2 = FileUpload.PostedFile.ContentType; string connectionString = WebConfigurationManager.ConnectionStrings["GSGA"].ConnectionString;
//Initialize SQL Server Connection SqlConnection con = new SqlConnection(connectionString);
//Set insert query string qry = "insert into Officers (Picture,PictureType ,PicttureTitle) values(@ImageData, @PictureType, @PictureTitle)";
//Initialize SqlCommand object for insert. SqlCommand cmd = new SqlCommand(qry, con);
//We are passing Original Image Path and Image byte data as sql parameters. cmd.Parameters.Add(new SqlParameter("@PictureTitle", str1));
cmd.Parameters.Add(new SqlParameter("@PictureType", str2));Stream imgStream = FileUpload.PostedFile.InputStream;
int imgLen = FileUpload.PostedFile.ContentLength;byte[] ImageBytes = new byte[imgLen]; cmd.Parameters.Add(new SqlParameter("@ImageData", ImageBytes));
//Open connection and execute insert query.
con.Open();
cmd.ExecuteNonQuery();
con.Close(); //Close form and return to list or images.
}
}
}
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.Source Error:
Line 32:
Line 33: string str2 = FileUpload.PostedFile.ContentType;
Line 34: string connectionString = WebConfigurationManager.ConnectionStrings["GSGA"].ConnectionString;
Line 35:
Line 36: //Initialize SQL Server Connection Source File: c:UsersManojDocumentsVisual Studio 2005WebSitesGSGABinaryfrmUpload.aspx.cs Line: 34
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Binary_frmUpload.btnUpload_Click(Object sender, EventArgs e) in c:UsersManojDocumentsVisual Studio 2005WebSitesGSGABinaryfrmUpload.aspx.cs:34
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
View 2 Replies
View Related
Aug 17, 2007
Hello All
Not sure if this is the right forum to post this question to, so if it's not, please accept my apologies.
I'm working in SQL Server 2005 with a database that was migrated to 2005 from SQL Server 2000. I have to alter a trigger on a table for some functionality changes, and when I modify the trigger and then access it through the application the database is working with, I receive this error:
There was a error in the [stored procedure name] procedure. Error Number: -2147217900 Error Description: [Microsoft][ODBC SQL Server Driver][SQL Server]The definition of object '[trigger name]' has changed since it was compiled.
[stored procedure name] and [trigger name] are where the actual names appear in the message.
I've tried running sp_recompile on the trigger, stored procedure, and table that are associated with this, and nothing works. I have dropped the trigger, which allows the save process to complete (but doesn't perform the required functionality, of course), and then re-created the trigger, but the error message still comes up. The compatibility level for the database is SQL Server 2000 (80) (as it was migrated from SQL Server 2000 as I mentioned above).
Has anyone seen this, and if so, how can I fix it?
Thanks in advance for your help!
Jay
View 4 Replies
View Related
Dec 21, 2006
Help! I have posted this before and I had hoped that the VS2005 SP1 would help my problem. It didn't. My code is shown below. I have dropped a sqlconnection, sqldataadapter and a strongly-typed dataset from the toolbox onto the component designer for my page and written my code. It compiles without any errors but at runtine I receive the system error "Object reference not set to an instance of an object." The error occurs at the first line where the sqldataadapter is mentioned. I have shufflled the code and the error still occurs at first mention of the dataadapter. I have set parameters to a simple string such as "myemail." It hasn't helped. I have used the "Dim" statement as "Dim DaAuthorLogin as System.Data.SqlClient.SqlDataadapter and Dim DaAuthorLogin as New ......) at the start of the private sub generated by the event requiring the data. Nothing helps. Here is my simple code to select data from a sqlserver 2000 database. Why do I continue to get this error?
Partial Class AuthorLogin
Inherits System.Web.UI.Page
Protected WithEvents AuthorInformation As System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommand
Me.DaAuthorLogin = New System.Data.SqlClient.SqlDataAdapter
Me.MDData = New System.Data.SqlClient.SqlConnection
Me.DsAuthorLogin = New MedicalDecisions.DsAuthorLogin
CType(Me.DsAuthorLogin, System.ComponentModel.ISupportInitialize).BeginInit()
'
'SqlSelectCommand1
'
Me.SqlSelectCommand1.CommandText = "SELECT AuthorAlias, AuthorEmail, AuthorPassword, LastName, PreferredName" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "FRO" & _
"M T_Author" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "WHERE (AuthorEmail = @AuthorEmail) AND (AuthorPassword =" & _
" @AuthorPassword)"
Me.SqlSelectCommand1.Connection = Me.MDData
Me.SqlSelectCommand1.Parameters.AddRange(New System.Data.SqlClient.SqlParameter() {New System.Data.SqlClient.SqlParameter("@AuthorEmail", System.Data.SqlDbType.NVarChar, 50, "AuthorEmail"), New System.Data.SqlClient.SqlParameter("@AuthorPassword", System.Data.SqlDbType.NVarChar, 50, "AuthorPassword")})
'
'DaAuthorLogin
'
Me.DaAuthorLogin.SelectCommand = Me.SqlSelectCommand1
Me.DaAuthorLogin.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "T_Author", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("AuthorAlias", "AuthorAlias"), New System.Data.Common.DataColumnMapping("AuthorEmail", "AuthorEmail"), New System.Data.Common.DataColumnMapping("AuthorPassword", "AuthorPassword"), New System.Data.Common.DataColumnMapping("LastName", "LastName"), New System.Data.Common.DataColumnMapping("PreferredName", "PreferredName")})})
'
'MDData
'
Me.MDData.ConnectionString = "Data Source=CIS1022DAVID;Initial Catalog=CGData;Integrated Security=True;Pooling" & _
"=False"
Me.MDData.FireInfoMessageEventOnUserErrors = False
'
'DsAuthorLogin
'
Me.DsAuthorLogin.DataSetName = "DsAuthorLogin"
Me.DsAuthorLogin.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema
CType(Me.DsAuthorLogin, System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Friend WithEvents SqlSelectCommand1 As System.Data.SqlClient.SqlCommand
Friend WithEvents MDData As System.Data.SqlClient.SqlConnection
Friend WithEvents DaAuthorLogin As System.Data.SqlClient.SqlDataAdapter
Friend WithEvents DsAuthorLogin As MedicalDecisions.DsAuthorLogin
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
'no code here
End Sub
Private Sub AuthorLoginRegister_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthorLoginRegister.Click
'for new author registration
Response.Redirect("AuthorInformation.aspx")
End Sub
Private Sub AuthorLoginBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthorLoginBack.Click
'to navigate back
Response.Redirect("MainPaths.aspx")
End Sub
Protected Sub AuthorLoginPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthorLoginPassword.TextChanged
'pass the parameters to the dataadapter and return dataset
DaAuthorLogin.SelectCommand.Parameters("@AuthorEmail").Value = AuthorLoginEmail.Text
DaAuthorLogin.SelectCommand.Parameters("@AuthorPassword").Value = AuthorLoginPassword.Text
MDData.Open()
DaAuthorLogin.Fill(DsAuthorLogin, "T_Author")
MDData.Close()
'set session objects
If DsAuthorLogin.T_Author.Rows.Count > 0 Then
Session("AuthorAlias") = DsAuthorLogin.T_Author(0).AuthorAlias
Session("LastName") = DsAuthorLogin.T_Author(0).LastName
Session("PreferredName") = DsAuthorLogin.T_Author(0).PreferredName
Response.Redirect("AuthorPaths.aspx")
Else : AuthorLoginNotValid.Visible = True
AuthorLoginEmail.Text = ""
AuthorLoginPassword.Text = ""
End If
End Sub
End Class
Thanks in advance,
David
View 2 Replies
View Related
Sep 12, 2006
Anyone know what this error means and how to get rid of it?
Public Sub Main()
Dim myMessage As Net.Mail.MailMessage
Dim mySmtpClient As Net.Mail.SmtpClient
myMessage.To(20) = New Net.Mail.MailAddress(me@hotmail.com)
myMessage.From = New Net.Mail.MailAddress(someone@microsoft.com)
myMessage.Subject = "as;dlfjsdf"
myMessage.Priority = Net.Mail.MailPriority.High
mySmtpClient = New Net.Mail.SmtpClient("microsoft.com")
mySmtpClient.Send(myMessage)
Dts.TaskResult = Dts.Results.Success
End Sub
Thanks,
View 4 Replies
View Related
Mar 17, 2008
Hi,
I am trying to develop a custom algorithm. I have implemented and tested training methods, however I fail at prediction phase. When I try to run a prediction query against a model created with my algorithm I get:
Executing the query ...
Obtained object of type: Microsoft.AnalysisServices.AdomdClient.AdomdDataReader
COM error: COM error: DMPluginWrapper; Object reference not set to an instance of an object..
Execution complete
I know this is not very descriptive, but I have seen that algorith doesn't even executes my Predict(..) function (I can test this by logging to a text file)
So the problem is this, when I run prediction query DMPluginWrapper gives exception -I think- even before calling my custom method.
As I said it is not a very descriptive message but I hope I have hit a general issue.
Thanks...
View 3 Replies
View Related
Apr 2, 2008
I am trying to send some data back to our as/400 from SQL server. Before I do so I need to delete entries from the table. I have an odbc connection set up and have used it sucessfully in a datareader compoenent but but when I try to use it for a delete SQL task it give me the followign error. what am I doing wrong? I even tried hardcoding in the system name/library name.
Here is my delete sql script
DELETE FROM DSSCNTL Where Companycode = 10
TITLE: SQL Task
------------------------------
Object reference not set to an instance of an object.
------------------------------
BUTTONS:
OK
------------------------------
View 7 Replies
View Related
Feb 15, 2007
When I try and run Report Builder Reports i get this error message "Object reference not set to an instance of an object. "
I can run reports locally but not from Report manager
here is the stack trace info
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Reporting.WebForms.WebRequestHelper.GetExceptionForMoreInformationNode(XmlNode moreInfo, XmlNamespaceManager namespaces) +18
Microsoft.Reporting.WebForms.WebRequestHelper.ExceptionFromWebResponse(Exception e) +358
Microsoft.Reporting.WebForms.ServerReport.ServerUrlRequest(Boolean isAbortable, String url, Stream outputStream, String& mimeType, String& fileNameExtension) +482
Microsoft.Reporting.WebForms.ServerReport.InternalRender(Boolean isAbortable, String format, String deviceInfo, NameValueCollection urlAccessParameters, Stream reportStream, String& mimeType, String& fileNameExtension) +958
Microsoft.Reporting.WebForms.ServerReportControlSource.RenderReport(String format, String deviceInfo, NameValueCollection additionalParams, String& mimeType, String& fileExtension) +84
Microsoft.Reporting.WebForms.ExportOperation.PerformOperation(NameValueCollection urlQuery, HttpResponse response) +143
Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) +75
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +154
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
View 3 Replies
View Related
May 13, 2015
Getting the following error-message:
OS: Windows Server 2008 R2 Standard
64bit
Office 2010
Power Pivot Tables are fed by Power Query queries.
View 3 Replies
View Related
Apr 8, 2008
Hi Everyone,
Please help me on this issue. I'm a new SSIS User.
I've installed Sql Server 2005 Developer Edition
When I create a new SSIS Project in Business Intelligence Development Studio,
I get the following message:
"Microsoft Visual Studio is unable to load this document: Object reference is not set to an instance of an object".
Error loading 'package.dtsx'bject reference is not set to an instance of an object
When I try to debug the package, I get the below message:
parameter Component(System.Design) is null.
I've uninstalled and installed SS 2005 several times, yet the problem persists.
Please help.
This is the package.dtsx
<?xml version="1.0"?><DTS:Executable xmlnsTS="www.microsoft.com/SqlServer/Dts" DTS:ExecutableType="MSDTS.Package.1"><DTSroperty DTS:Name="PackageFormatVersion">2</DTSroperty><DTSroperty DTS:Name="VersionComments"></DTSroperty><DTSroperty DTS:Name="CreatorName">USkothand1</DTSroperty><DTSroperty DTS:Name="CreatorComputerName">US6051KOTHAND1</DTSroperty><DTSroperty DTS:Name="CreationDate" DTSataType="7">4/8/2008 10:53:39 AM</DTSroperty><DTSroperty DTS:Name="PackageType">5</DTSroperty><DTSroperty DTS:Name="ProtectionLevel">1</DTSroperty><DTSroperty DTS:Name="MaxConcurrentExecutables">-1</DTSroperty><DTSroperty DTS:Name="PackagePriorityClass">0</DTSroperty><DTSroperty DTS:Name="VersionMajor">1</DTSroperty><DTSroperty DTS:Name="VersionMinor">0</DTSroperty><DTSroperty DTS:Name="VersionBuild">0</DTSroperty><DTSroperty DTS:Name="VersionGUID">{FBD98635-EDDE-4F58-9D53-356E8CB653FB}</DTSroperty><DTSroperty DTS:Name="EnableConfig">0</DTSroperty><DTSroperty DTS:Name="CheckpointFileName"></DTSroperty><DTSroperty DTS:Name="SaveCheckpoints">0</DTSroperty><DTSroperty DTS:Name="CheckpointUsage">0</DTSroperty><DTSroperty DTS:Name="SuppressConfigurationWarnings">0</DTSroperty><DTSroperty DTS:Name="ForceExecValue">0</DTSroperty><DTSroperty DTS:Name="ExecValue" DTSataType="3">0</DTSroperty><DTSroperty DTS:Name="ForceExecutionResult">-1</DTSroperty><DTSroperty DTS:Name="Disabled">0</DTSroperty><DTSroperty DTS:Name="FailPackageOnFailure">0</DTSroperty><DTSroperty DTS:Name="FailParentOnFailure">0</DTSroperty><DTSroperty DTS:Name="MaxErrorCount">1</DTSroperty><DTSroperty DTS:Name="ISOLevel">1048576</DTSroperty><DTSroperty DTS:Name="LocaleID">1033</DTSroperty><DTSroperty DTS:Name="TransactionOption">1</DTSroperty><DTSroperty DTS:Name="DelayValidation">0</DTSroperty>
<DTS:LoggingOptions><DTSroperty DTS:Name="LoggingMode">0</DTSroperty><DTSroperty DTS:Name="FilterKind">1</DTSroperty><DTSroperty DTS:Name="EventFilter" DTSataType="8"></DTSroperty></DTS:LoggingOptions><DTSroperty DTS:Name="ObjectName">Package</DTSroperty><DTSroperty DTS:Name="DTSID">{191D188C-EA6E-46D6-A46A-8C9F3C21C321}</DTSroperty><DTSroperty DTS:Name="Description"></DTSroperty><DTSroperty DTS:Name="CreationName">MSDTS.Package.1</DTSroperty><DTSroperty DTS:Name="DisableEventHandlers">0</DTSroperty></DTS:Executable>
Thanks
Best Regards
View 12 Replies
View Related
Mar 6, 2007
I created an xmldocument which I would like to insert in a db field with the data type XML.The following code is giving me the error:System.Data.SqlClient.SqlException: XML parsing: line 1, character 38, unable to
switch the encoding SqlCommand cmdUpdate = new SqlCommand("sp_AddHistory", sqlConnection); cmdUpdate.CommandType = CommandType.StoredProcedure; cmdUpdate.Parameters["@FieldsChanged"].Value = xmlDoc.innerXML; // don't know whether this is good cmdUpdate.ExecuteNonQuery(); innerXML:<?xml version="1.0" encoding="utf-8"?><Fields> <Field> <FieldName>comp_Area</FieldName> <OldValue>Area 52</OldValue> <NewValue>Area 51</NewValue> </Field></Fields> The XML seems fine.. any ideas?
View 3 Replies
View Related
May 10, 2007
Hi! I need to know what can I do to use a variable in the WHERE condition of the sqlcommand as I show you: current_user = User.Identity.Name
Dim cmd As New SqlCommand("SELECT [id_usuario], [nombre], [apellidos], [telefono], [empresa] FROM [usuario] WHERE [id_usuario] = current_user", cn) Obviously it doesn't work and I need your help. Thanks.
View 7 Replies
View Related
Oct 17, 2007
Hello,
I am trying to insert a value into a specific row in a table. The error comes from the myCommand2 statement but i don't know how to solve it. Please help!
My code is as follows:SqlCommand myCommand = new SqlCommand("select count(*) from updatetable", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
int count = myReader.GetInt32(0);
SqlCommand myCommand2 = new SqlCommand("insert into interface (Total) where description = 'Graphicads' value ( " + count + ")", myConnection2);myCommand2.CommandType = CommandType.Text;
myCommand2.ExecuteNonQuery();
View 4 Replies
View Related
Oct 26, 2007
Hi,When using the following controls....System.Data.SqlClient.SqlConnection System.Data.SqlClient.SqlCommandIf I want to change my SQL command and execute the query once again what cleanup do I need to do first?Do I need close and dispose the SqlConnection?Do I need to dispose the SqlCommand?Can I use the SqlConnection for more than one SqlCommand?Thanks,Scott
View 5 Replies
View Related
Nov 23, 2007
Hello all, when I write my CommandText, It displays it as insert into videos values (127.0.0.1, 4000, 434), which the ip address is sent int as a string, put i keep getting an error, and I think it is because it is wanting an string, but it is sending in these "." or something, anyways heres my method, I dont know how I can add " " around the ip when i pass it in, since it is a string. thanks.
1 [WebMethod]
2 public void Register(string ip, int port, int[] handles)
3 {
4 SqlConnection dbConn = new SqlConnection(connStr);
5 SqlCommand comm = new SqlCommand();
6 comm.Connection = dbConn;
7 dbConn.Open();
8 for (int i = 0; i < handles.Length; i++)
9 {
10 comm.CommandText = "insert into videos values (" + ip + ", " + port + ", " + handles[i] + ")";
11 comm.ExecuteNonQuery();
12 }
13 dbConn.Close();
14 }
View 1 Replies
View Related
Mar 12, 2008
Using SqlCommand, this is how I am updating a database table:
Sub UpdateDataGrid(obj As Object, ea As DataGridCommandEventArgs) strSQL = "UPDATE Basket SET Quantity = Qty, Total = TotAmt WHERE BasketID = BID AND ProductID = PID" sqlCmd = New SqlCommand(strSQL, sqlConn) With sqlCmd .Parameters.Add("Qty", SqlDbType.Int).Value = CInt(iQty) .Parameters.Add("TotAmt", SqlDbType.Money).Value = CInt(iQty) * CType(ea.Item.FindControl("lblPrice"), Label).Text .Parameters.Add("BID", SqlDbType.VarChar, 50).Value = strBasketID .Parameters.Add("PID", SqlDbType.VarChar, 50).Value = CType(ea.Item.FindControl("lblID"), Label).Text End With sqlConn.Open() sqlCmd.ExecuteNonQuery() sqlConn.Close()End Sub
But the above code generates the following error pointing to the red colored line in the above code:
Invalid column name 'BID'.Invalid column name 'PID'.
BID & PID are not the column names in the actual database table but can't it be done in the way I have done above? In fact, Qty & TotAmt are not the column names in the actual database table as well; so why isn't the error pointing to Qty & TotAmt as they will be evaluated before BID & PID, if I am not mistaken?
View 8 Replies
View Related
Apr 15, 2008
How can I check if the ( SqlCommand ) return empty values
Can some one write code for this, I want know it is return Null values or not
thanx ....
View 4 Replies
View Related
Feb 19, 2006
I want to do something like the following but I get an error: Object reference not set to an instance of an object. SqlConnection sqlConnection = new SqlConnection("server=xxxxx"); SqlCommand [] cmd = new SqlCommand[3]; Object returnValue; cmd[0].CommandText = "DO QUERY"; cmd[1].CommandText = "DO QUERY"; cmd[2].CommandText = "DO QUERY"; cmd[3].CommandText = "DO QUERY"; } sqlConnection.Open();int i = 0;while(i<4){ cmd[i].CommandType = CommandType.Text; cmd[i].Connection = sqlConnection; cmd[i].ExecuteNonQuery(); returnValue[i] = cmd[i].ExecuteScalar();i++} sqlConnection.Close();How should I do the followingThanks
View 9 Replies
View Related
Mar 7, 2006
How to test @au_lname's value sends to the following following sql command?
Dim MyCommand As New SqlCommand("UPDATE [authors] SET [au_lname] = @au_lname", MyConnection)MyCommand.Parameters.Add(New SqlParameter("@au_lname", SqlDbType.NVarChar)).Value = me.au_lname.text
I tried to print the "MyCommand.CommandText.ToString" but only get UPDATE [authors] SET [au_lname] = @au_lname with no value in the command text.
Thanks!
View 5 Replies
View Related
May 4, 2006
Is there documentation on what ExecuteScalar() will return if the SQL statement is returning an image?
View 1 Replies
View Related
May 17, 2006
Hi:
I am using sqlcommand.parameters.add() and up to 74 parameters for one sqlcommand, it gets the error "too many parameters for the sqlcommand", I wonder if someone know is there limitation of the paramters that I can pass to sqlcommand? If so, how many parameters I can pass to the sqlcommand at one time?
thank u in adv.
View 4 Replies
View Related
May 30, 2006
Hello,I was trying to do the following: Dim cmd As SqlCommand Dim objConnection As SqlConnection objConnection = New SqlConnection = Web.configwhere the We.config is where my connection string is set. but I get a sintax error in the Web.config line.is it possible to asign the value of the web.config content to the new sql connection?thanks for any suggestions.
View 1 Replies
View Related
May 27, 2008
Hi All,
i have a table in MS Access with CandidateId and Image column. Image column is in OLE object format. i need to move this to SQL server 2005 with CandidateId column with integer and candidate Image column to Image datatype.
its very udgent, i need any tool to move this to SQL server 2005 or i need a code to move this table from MS Access to SQL server 2005 in C#.
please do the needfull ASAP. waiting for your reply
with regards
View 1 Replies
View Related
May 22, 2008
Just installed VS 2005 & SQLServer 2005 clients on my workstation. When trying to create a new Integration Services Project and start work in the designer receive the MICROSOFT VISUAL STUDIO 'Object reference not set to an instance of an object.' dialog box with message "Creating project 'Integration Services project1'...project creation failed."
Previously I had SQLServer 2000 client with the little VS tool that came with it installed. Uninstalled these prior to installing the 2005 tools (VS and SQLServer).
I'm not finding any information on corrective action for this error.
Any one have this problem and found the solution?
Thanks,
CLC
View 1 Replies
View Related
Dec 28, 2004
Each time I press submit to insert data into the database I receive the following message. I use the same code on another page and it works fine. Here is the error:
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 125: MyCommand.Parameters("@Balance").Value = txtBalance.Text
Line 126:
Line 127: MyCommand.Connection.Open()
Line 128:
Line 129: Try
Source File: c:inetpubwwwrootCreditRepairCreditor_Default.aspx.vb Line: 127
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
CreditRepair.CreditRepair.Vb.Creditor_Default.btnSaveAdd_Click(Object sender, EventArgs e) in c:inetpubwwwrootCreditRepairCreditor_Default.aspx.vb:127
System.Web.UI.WebControls.Button.OnClick(EventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain()
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If (Page.IsValid) Then
Dim DS As DataSet
Dim MyCommand As SqlCommand
Dim AddAccount As String = "insert into AccountDetails (Account_ID, Report_ID, Balance) values (@Account_ID, @Report_ID, @Balance)"
MyCommand = New SqlCommand(AddAccount, MyConnection)
MyCommand.Parameters.Add(New SqlParameter("@Account_ID", SqlDbType.Char, 50))
MyCommand.Parameters("@Account_ID").Value = txtAccount_ID.Text
MyCommand.Parameters.Add(New SqlParameter("@Report_ID", SqlDbType.Char, 50))
MyCommand.Parameters("@Report_ID").Value = txtReport_ID.Text
MyCommand.Parameters.Add(New SqlParameter("@Balance", SqlDbType.Char, 50))
MyCommand.Parameters("@Balance").Value = txtBalance.Text
MyCommand.Connection.Open()
MyCommand.ExecuteNonQuery()
Response.Redirect("Customer_Details.aspx?SS='CustHeadGrid.Columns[0].Item.lblSS.Text)")
MyCommand.Connection.Close()
End If
View 2 Replies
View Related
Sep 13, 2006
I am trying to execute this code feom Script task while excuting its giving me error that "Object reference not set to an instance of an object." The assemblies Iam referening in this code are there in GAC. Any idea abt this.
Thanks,
Public Sub Main()
Dim remoteUri As String
Dim fireAgain As Boolean
Dim uriVarName As String
Dim fileVarName As String
Dim httpConnection As Microsoft.SqlServer.Dts.Runtime.HttpClientConnection
Dim emptyBytes(0) As Byte
Dim SessionID As String
Dim CusAuth As CustomAuth
Try
' Determine the correct variables to read for URI and filename
uriVarName = "vsReportUri"
fileVarName = "vsReportDownloadFilename"
' create SessionID for use with HD Custom authentication
CusAuth = New CustomAuth(ASCIIEncoding.ASCII.GetBytes(Dts.Variables("in_vsBatchKey").Value.ToString()))
Dts.Variables(uriVarName).Value = Dts.Variables(uriVarName).Value.ToString() + "&" + _
"BeginDate=" + Dts.Variables("in_vsBeginDate").Value.ToString() + "&" + _
"EndDate=" + Dts.Variables("in_vsEndDate").Value.ToString()
Dim request As HttpWebRequest = CType(WebRequest.Create(Dts.Variables(uriVarName).Value.ToString()), HttpWebRequest)
'Set credentials based on the credentials found in the variables
request.Credentials = New NetworkCredential(Dts.Variables("in_vsReportUsername").Value.ToString(), _
Dts.Variables("in_vsReportPassword").Value.ToString(), _
Dts.Variables("in_vsReportDomain").Value.ToString())
'Place the custom authentication session ID in a cookie called BatchSession
request.CookieContainer.Add(New Cookie("BatchSession", CusAuth.GenerateSession("EmailAlertingSSIS"), "/", Dts.Variables("in_vsReportDomain").Value.ToString()))
' Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4
request.MaximumResponseHeadersLength = 4
' Prepare to download, write messages indicating download start
Dts.Events.FireInformation(0, String.Empty, String.Format("Downloading '{0}' from '{1}'", _
Dts.Variables(fileVarName).Value.ToString(), Dts.Variables(uriVarName).Value.ToString()), String.Empty, 0, fireAgain)
Dts.Log(String.Format("Downloading '{0}' from '{1}'", Dts.Variables(fileVarName).Value.ToString(), Dts.Variables(uriVarName).Value.ToString()), 0, emptyBytes)
' Download data
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
' Get the stream associated with the response.
Dim receiveStream As Stream = response.GetResponseStream()
' Pipes the stream to a higher level stream reader with the required encoding format.
Dim readStream As New StreamReader(receiveStream, Encoding.UTF8)
Dim fileStream As New StreamWriter(Dts.Variables(fileVarName).Value.ToString())
fileStream.Write(readStream.ReadToEnd())
fileStream.Flush()
fileStream.Close()
readStream.Close()
fileStream.Dispose()
readStream.Dispose()
'Download the file and report success
Dts.TaskResult = Dts.Results.Success
Catch ex As Exception
' post the error message we got back.
Dts.Events.FireError(0, String.Empty, ex.Message, String.Empty, 0)
Dts.TaskResult = Dts.Results.Failure
End Try
End Sub
View 1 Replies
View Related
Nov 14, 2006
Hi all,
I'm getting this problem 'Object reference not set to an instance of an object.' whenever I try to review a report and I checked the log file and this is what it had
w3wp!ui!1!11/14/2006-10:54:20:: Unhandled exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Reporting.WebForms.WebRequestHelper.GetExceptionForMoreInformationNode(XmlNode moreInfo, XmlNamespaceManager namespaces)
at Microsoft.Reporting.WebForms.WebRequestHelper.ExceptionFromWebResponse(Exception e)
at Microsoft.Reporting.WebForms.ServerReport.ServerUrlRequest(Boolean isAbortable, String url, Stream outputStream, String& mimeType, String& fileNameExtension)
at Microsoft.Reporting.WebForms.ServerReport.GetStyleSheet(String styleSheetName)
at Microsoft.Reporting.WebForms.ReportServerStyleSheetOperation.PerformOperation(NameValueCollection urlQuery, HttpResponse response)
at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Some previous forums stated checking the webconfig file but the web config file look okay. Is there another way to fix this.
Much Thanks,
Carl
View 3 Replies
View Related
Jan 14, 2008
Hello -
For the life of me I cannot figure out why i'm getting the "Object Refence Not Set To an Instance of An Object" error after I try and create a Report Services project in Business Intelligence Studio. I've followed all of the steps in similar posts such as checking the ReportServer/web.config file but everything checks out.
Does anyone have any other ideas as to how I can get rid of this annoying error and start creating some reports?
Thanks!!!
View 3 Replies
View Related
Dec 27, 2007
Hello,
I've ran into trouble while creating a rather simple transformation script component (one input, one output). The only thing it has to do is test the values coming from it's input rows and set the values of the output rows according to some rules; something like:
Code Block
Public Overrides Sub InputBrowser_ProcessInputRow(ByVal Row As InputBrowserBuffer)
If Row.UserAgent.Contains("MSIE") Then 'test input
Row.BrowserName = "Internet Explorer" 'set output
End If
End Sub
This raises an "Object reference not set to an instance of an object." exception. Commenting out the input (Row.UserAgent) solves the exception, but I actually do need to test the contents of the input row (and by leaving only the output manipulation, the script won't reach it's end, the components remain yellow). What can I do about this?
Thanks in advance!
View 5 Replies
View Related