Solved

Updating a Record in a SQL DB from a C# Console

Posted on 2009-04-15
11
198 Views
Last Modified: 2013-12-17
Ok, I was just running some tests and the same record was added again.
I'm trying to figure out how the C# Code is supposed to know what it needs to do to check the ID on the database, look for that record, and if the record exists, then Update. So, it looks like my C# Code is trying to add an ID Value when all it should do is check for existance on DB.
Below is the code in C# and my Stored Procedure. I appreciate any help to remedy the problem code below.
Thanks Experts!
Wally
------------------ C# Code -------------------------
foreach (ManagementObject csObjQueried in csObjSearcher.Get())
                            {
                                try
                                {
                                    sqlCmd2.Parameters.Add("ID", System.Data.SqlDbType.Int).Value = "ID" ;
                                    sqlCmd2.Parameters.AddWithValue("WorkstationName", csObjQueried["Name"]);
                                    sqlCmd2.Parameters.AddWithValue("UserName", csObjQueried["UserName"]);
                                    sqlCmd2.Parameters.AddWithValue("Domain", csObjQueried["Domain"]);
                                    sqlCmd2.Parameters.AddWithValue("WkstnStatus", csObjQueried["Status"]);
                                    //sqlCmd2.Parameters.AddWithValue("WakeUpType", csObjQueried["WakeUpType"]);
                                }
                                catch (Exception ex)
                                {
                                    sw.WriteLine("No Win32_ComputerSystem WMI Data returned for " + client.Wkstn + ".\nError is " +
                                            ex.Message);
                                    sw.Flush();
                                }
                            }
-------------------------------- STORED PROCEDURE --------------------------------
USE WMIDATA
GO
 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Wally Davis
-- Create date: April 13, 2009
-- Description:	
-- =============================================
 
ALTER PROCEDURE dbo.usp_InsertToWMIDATA
	-- Add the parameters for the stored procedure here
	@ID int,
	@WorkstationName varchar(15),
	@UserName varchar(15),
	@Domain varchar(50),
	@WkstnStatus varchar(10) = NULL,
	@MacAddress varchar(17)
AS
If @WorkstationName is not null
BEGIN
	INSERT INTO Main(WorkstationName, UserName, Domain, WkstnStatus, MacAddress)
	Values (@WorkstationName, @UserName, @Domain, @WkstnStatus, @MacAddress)
	SET @ID = SCOPE_IDENTITY()
END
ELSE
BEGIN
	UPDATE Main 
		SET WorkstationName = @WorkstationName, 
			UserName = @UserName,
			Domain = @Domain, 
			WkstnStatus = @WkstnStatus,
			MacAddress = @MacAddress
	WHERE ID = @ID
END
GO

Open in new window

0
Comment
Question by:wally_davis
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
11 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24150333
Why not modify your stored procedure to do the checking?
-- STORED PROCEDURE
 
alter procedure dbo.usp_InsertToWMIDATA
		@ID int,
		@WorkstationName varchar(15),
		@UserName varchar(15),
		@Domain varchar(50),
		@WkstnStatus varchar(10) = NULL,
		@MacAddress varchar(17)
AS
BEGIN
	IF EXISTS (SELECT COUNT(1) FROM Main WHERE ID = @ID)
		UPDATE Main
		SET WorkstationName = @WorkstationName,
		    UserName = @UserName,
		    Domain = @Domain,
		    WkstnStatus = @WkstnStatus,
		    MacAddress = @MacAddress
		WHERE ID = @ID
	ELSE
		INSERT INTO Main (WorkstationName, UserName, Domain, WkstnStatus, MacAddress)
		VALUES (@WorkstationName, @UserName, @Domain, @WkstnStatus, @MacAddress)
END
 
 
// C#
 
foreach (ManagementObject csObjQueried in csObjSearcher.Get())
{
    try
    {
        sqlCmd2.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = "ID" ;
        sqlCmd2.Parameters.AddWithValue("@WorkstationName", csObjQueried["Name"]);
        sqlCmd2.Parameters.AddWithValue("@UserName", csObjQueried["UserName"]);
        sqlCmd2.Parameters.AddWithValue("@Domain", csObjQueried["Domain"]);
        sqlCmd2.Parameters.AddWithValue("@WkstnStatus", csObjQueried["Status"]);
        
        sqlCmd2.CommandType = CommandType.StoredProcedure;
        sqlCmd2.ExecuteNonQuery("dbo.usp_InsertToWMIDATA");
    }
    catch (Exception ex)
    {
        sw.WriteLine("No Win32_ComputerSystem WMI Data returned for " + client.Wkstn + ".\nError is " +
                ex.Message);
        sw.Flush();
    }
}

Open in new window

0
 

Author Comment

by:wally_davis
ID: 24150546
After updating the code, I get this error "Failed to convert parameter value from a String to a Int32". That must have something to do with passing the ID to @ID as a parameter.
So, I shouldn't pass anything in really.......correct? and if that is correct, how do I adjust the code so that the SP also doesn't expect a Parameter.
0
 

Author Comment

by:wally_davis
ID: 24150567
Thinking about it again. ID should be = to something shouldn't it? So, if I pass in something to @ID, I think a call or some Select statement should be run to find the ID on the specific workstation before an update could be made.
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24150754
I took your ID column to be an auto-increment field that would just add 1 every time a record is inserted. Is this correct? If not, what is the ID column for?
0
 

Author Comment

by:wally_davis
ID: 24150814
Correct, the ID Column is an Identity / PK Column. I understand how the Inserts are working, but, how is the actual C# Code going to hunt down the specific workstation client's Identity ID in order to know what record to update?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24150896
Other than ID, which fields are unique to a workstation? Workstation name I presume?
0
 

Author Comment

by:wally_davis
ID: 24151300
Correct, just the Workstation Name.
0
 

Accepted Solution

by:
wally_davis earned 0 total points
ID: 24162966
Expert never returned to answer my issue. If Expert doesn't respond in 48 hours please delete this question. I will ask this question again in another thread if no response.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24163052
My apologies. I was having a rough time figuring out how to set rules to move emails in my email client. I think EE's mail was a victim of this. Back to the issue...


I attached some modifications. Since workstation name is unique, we can identify a record in the database. The id column is auto-generated so we don't need to pass in anything for that.
-- STORED PROCEDURE
 
alter procedure dbo.usp_InsertToWMIDATA
                @WorkstationName varchar(15),
                @UserName varchar(15),
                @Domain varchar(50),
                @WkstnStatus varchar(10) = NULL,
                @MacAddress varchar(17)
AS
BEGIN
        IF EXISTS (SELECT COUNT(1) FROM Main WHERE WorkstationName = @WorkstationName)
                UPDATE Main
                SET UserName = @UserName,
                    Domain = @Domain,
                    WkstnStatus = @WkstnStatus,
                    MacAddress = @MacAddress
                WHERE  WorkstationName = @WorkstationName
        ELSE
                INSERT INTO Main (WorkstationName, UserName, Domain, WkstnStatus, MacAddress)
                VALUES (@WorkstationName, @UserName, @Domain, @WkstnStatus, @MacAddress)
END
 
 
// C#
 
foreach (ManagementObject csObjQueried in csObjSearcher.Get())
{
    try
    {
        sqlCmd2.Parameters.AddWithValue("@WorkstationName", csObjQueried["Name"]);
        sqlCmd2.Parameters.AddWithValue("@UserName", csObjQueried["UserName"]);
        sqlCmd2.Parameters.AddWithValue("@Domain", csObjQueried["Domain"]);
        sqlCmd2.Parameters.AddWithValue("@WkstnStatus", csObjQueried["Status"]);
        
        sqlCmd2.CommandType = CommandType.StoredProcedure;
        sqlCmd2.ExecuteNonQuery("dbo.usp_InsertToWMIDATA");
    }
    catch (Exception ex)
    {
        sw.WriteLine("No Win32_ComputerSystem WMI Data returned for " + client.Wkstn + ".\nError is " +
                ex.Message);
        sw.Flush();
    }
}

Open in new window

0
 

Author Comment

by:wally_davis
ID: 24169399
kaufmed. I tested it and this allowed Updates to work perfectly. I'll accept your solution but I really need you to answer this other question first with respect to the Workstation being unique. I have not added the "WorkstationName" column in my table to the Table Designer/Indexes...Keys/Column Property as a "Unique" column. Should I add that column as a Unique ID? I would imagine adding it would make sense but there may also be a reason not too. Thanks!
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24171068
Adding a Unique constraint to your database column ensures that if you try to add a record with a particular Workstation Name, and that name already exists in a record, then you will get an error (which you can catch/handle) when the new record is attempted to be added. There's nothing saying you do or do not have to do it this way, but I would imagine having it might be more beneficial than not. Of course, there will be a little overhead in checking the table for uniqueness when you add records, but I would perceive it as negligible compared to database integrity.

I hope that made sense :)
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question