473,387 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

updatecommand

Hi,
I am trying to update the customer table by using the updatecommd,
please see
below, however, when it runs it does not fire the update statement. I
ran the sql profiler
and the only statement the profiler shows is the 'Select * from
Customers...' and zero
rows updated.

Does any knwo why the updatecommand does not fire.

Thanks in advance

Regards,
----------------------------------------------------------------------------------------
.... code sample
cmd = New SqlClient.SqlCommand("Select * from
Northwind.dbo.Customers ", consql)
adapter.SelectCommand = cmd
' read customer table
adapter.Fill(datatable1)

' update customer
cmd = New SqlClient.SqlCommand("UPDATE
Northwind.dbo.Customers SET CustomerID =
@CustomerID, CompanyName =
@CompanyName "& _
"WHERE CustomerID =
@oldCustomerID", consql)

cmd .Parameters.Add("@CustomerID", SqlDbType.NVarChar, 10, "CustomerID")
cmd .Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")

' update database
adapter.UpdateCommand = cmd
adapter.Update(datatable1)


May 13 '06 #1
5 1386
Wandii,

http://www.vb-tips.com/default.aspx?...2-d7c12bbb3726

We have a problem at the moment with showing links on our website.

Therefore is here the text.

This sample is to show the following items for an SQLServer Database
Creating by hand the select, insert, update, delete commands including the
parameters
Filling that table
Showing that table with negative seeded identnumbers
Update that table (you can edit the table)

Not implemented is any error handling beside showing that there is an error
(not at the places where that in fact cannot happen in this sample).

You need for this a new project, drag in a DataGridView and a Button on the
form and paste this code in the class. (Although it is 2005 is it as well to
use with 2003 where you than have to change the DataGridView for a DataGrid
and some of the code.

If you want to use another DataBaseName change that name at DBName, be aware
that it in advance of the sample every time will be Droped (Deleted).
--------------------------------------------------------------------------------

Imports System.Data.sqlclient
Imports System.Data
Public Class Form1
Private DBName As String = "TestDataBaseAutoNumber"
Private ConnString As String
Friend da As New SqlDataAdapter
Friend Conn As New SqlConnection
Dim dt As New DataTable

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'To have a test is a very very small database created
CreateNewsqlDatabase(DBName)
'In this parts are the commands
CreateCommands()
'
'This part is to test the sample
da.FillSchema(dt, SchemaType.Mapped)
Dim col As DataColumn = dt.Columns(0)
col.AutoIncrement = True
col.AutoIncrementSeed = -1
col.AutoIncrementStep = -1
For i As Integer = 0 To 3
dt.Rows.Add(dt.NewRow)
dt.Rows(i)(1) = ChrW(i + 65)
Next
dt.DefaultView.Sort = "WhatEver"
'
'the situation is only showed in the Datagrid
'the click on the button does the update
DataGridView1.DataSource = dt
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
BindingContext("dt").EndCurrentEdit()
da.Update(dt)
End Sub

Public Sub CreateCommands()
Dim nb As Byte = 0
Dim cmdSelect As New SqlCommand
Dim cmdInsert As New SqlCommand
Dim cmdUpdate As New SqlCommand
Dim cmdDelete As New SqlCommand
da.DeleteCommand = cmdDelete
da.InsertCommand = cmdInsert
da.SelectCommand = cmdSelect
da.UpdateCommand = cmdUpdate
da.TableMappings.AddRange(New Common.DataTableMapping() _
{New Common.DataTableMapping("Table", _
"Sample", New Common.DataColumnMapping() {New
Common.DataColumnMapping("AutoId", "AutoId"), _
New Common.DataColumnMapping("WhatEver", "WhatEver")})})
'
'cmdSelect
cmdSelect.CommandText = "SELECT AutoId, WhatEver FROM Sample"
cmdSelect.Connection = Conn
'
'cmdInsert
cmdInsert.CommandText = "INSERT INTO Sample(WhatEver) " & _
"VALUES (@WhatEver); SELECT AutoId, " & _
"WhatEver FROM Sample WHERE (AutoId = Scope_Identity())"
cmdInsert.Connection = Conn
cmdInsert.Parameters.Add(New SqlParameter("@AutoId", SqlDbType.Int,
4, "AutoId"))
cmdInsert.Parameters.Add(New SqlParameter("@WhatEver",
SqlDbType.NVarChar, 50, "WhatEver"))
'
'cmdUpdate
cmdUpdate.CommandText = "UPDATE Sample SET WhatEver = @WhatEver
WHERE (AutoId = @Original_AutoId) " & _
"AND (WhatEver = @Original_WhatEver OR @Original_WhatEver IS NULL
AND WhatEver IS NULL); " & _
"SELECT AutoId, WhatEver FROM Sample WHERE (AutoId = @AutoId)"
cmdUpdate.Connection = Conn
cmdUpdate.Parameters.Add(New SqlParameter("@AutoId", SqlDbType.Int,
4, "AutoId"))
cmdUpdate.Parameters.Add(New SqlParameter("@WhatEver",
SqlDbType.NVarChar, 50, "WhatEver"))
cmdUpdate.Parameters.Add(New SqlParameter("@Original_AutoId",
SqlDbType.Int, 4, _
ParameterDirection.Input, False, nb, nb, _
"AutoId", DataRowVersion.Original, Nothing))
cmdUpdate.Parameters.Add(New SqlParameter("@Original_WhatEver", _
SqlDbType.NVarChar, 50, ParameterDirection.Input, False, nb, nb, _
"WhatEver", DataRowVersion.Original, Nothing))
'
'cmdDelete
cmdDelete.CommandText = "DELETE FROM Sample WHERE (AutoId =
@Original_AutoId) AND " & _
"(WhatEver = @Original_WhatEver OR @Original_WhatEver IS NULL AND
WhatEver IS NULL)"
cmdDelete.Connection = Conn
cmdDelete.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@Original_Auto Id", _
System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input,
_
False, nb, nb, "AutoId", System.Data.DataRowVersion.Original,
Nothing))
cmdDelete.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@Original_What Ever", _
System.Data.SqlDbType.NVarChar, 50,
System.Data.ParameterDirection.Input, False, _
nb, nb, "WhatEver", System.Data.DataRowVersion.Original, Nothing))
End Sub

Private Sub CreateNewsqlDatabase(ByVal DbName As String)
Dim ConnString As String = "Server = .\SQLExpress; Database = ;
Integrated Security = SSPI"
Conn = New SqlConnection(ConnString)
Dim strSQL As String = "if Exists (Select * From
master..sysdatabases Where Name = '" & DbName & "')"
strSQL += " DROP DATABASE " & DbName & ";" & vbCrLf
strSQL += " CREATE DATABASE " & DbName
Dim cmd As New SqlCommand(strSQL, Conn)
executecmd(cmd)
Conn.ConnectionString = "Server = .\SQLExpress; Database =" & DbName
& " ; Integrated Security = SSPI"
cmd.Connection = Conn
cmd.CommandText = "CREATE TABLE Sample ( " & _
"AutoId int identity NOT NULL," & _
"WhatEver NVarchar(50)," & _
"CONSTRAINT [pk_AutoId] PRIMARY KEY (AutoId)) "
executecmd(cmd)
End Sub

Private Sub executecmd(ByVal cmd As SqlCommand)
Try
Conn.Open()
cmd.ExecuteNonQuery()
Catch ex As SqlException
MessageBox.Show(ex.Message, "sqlException")
Exit Sub
Catch ex As Exception
MessageBox.Show(ex.Message, "GeneralException")
Exit Sub
Finally
Conn.Close()
End Try
End Sub
End Class
Cor

"wandii" <wa****@yahoo.com> schreef in bericht
news:11**********************@y43g2000cwc.googlegr oups.com...
Hi,
I am trying to update the customer table by using the updatecommd,
please see
below, however, when it runs it does not fire the update statement. I
ran the sql profiler
and the only statement the profiler shows is the 'Select * from
Customers...' and zero
rows updated.

Does any knwo why the updatecommand does not fire.

Thanks in advance

Regards,
----------------------------------------------------------------------------------------
... code sample
cmd = New SqlClient.SqlCommand("Select * from
Northwind.dbo.Customers ",
consql)
adapter.SelectCommand = cmd
' read customer table
adapter.Fill(datatable1)

' update customer
cmd = New SqlClient.SqlCommand("UPDATE
Northwind.dbo.Customers SET CustomerID =
@CustomerID, CompanyName =
@CompanyName "& _
"WHERE CustomerID =
@oldCustomerID", consql)

cmd .Parameters.Add("@CustomerID", SqlDbType.NVarChar,

10,
"CustomerID")
cmd .Parameters.Add("@CompanyName", SqlDbType.NVarChar,

40,
"CompanyName")

' update database
adapter.UpdateCommand = cmd
adapter.Update(datatable1)

May 13 '06 #2
Thanks Cor for the quick respone. Actually I was hoping if someone
could pinpoint the
problem with my update codes. Why updatecommand would not fire? If I
use the
ExecuteNonQuery() instead of update(datatable1) then update works fine,
but why?

Regards

May 14 '06 #3
Wandii,

In my idea is your update command not equal to the one in the sample. I miss
at least the reading of the current item from the database to check to the
old one

Cor

"wandii" <wa****@yahoo.com> schreef in bericht
news:11*********************@j33g2000cwa.googlegro ups.com...
Thanks Cor for the quick respone. Actually I was hoping if someone
could pinpoint the
problem with my update codes. Why updatecommand would not fire? If I
use the
ExecuteNonQuery() instead of update(datatable1) then update works fine,
but why?

Regards

May 14 '06 #4
Cor,
I tried another simple block of codes, but still not updating the
database and doesn't throw an exception. Again if I
use the ExecuteNonQuery() it updates the database. I can see reading
the table in the Sql Profiler, however, no update. Any idea?

Thanks in advace.

--------------------------------------------------------------
' select statement
cmd = New SqlClient.SqlCommand("Select CaseID, UserID from
dbo.CaseToClose", consql)
adapter.SelectCommand = cmd
adapter.Fill(datatable)

' update statment
cmd = New SqlClient.SqlCommand(" UPDATE dbo.CaseToClose set
DateCompleted = Null, StatusID = 3 " +_
" WHERE CaseID = @CaseID" + _
" AND ProblemTypeID =
@ProblemType ", consql)

cmd.Parameters.Add("@CaseID", SqlDbType.VarChar, 10).Value =
sCaseNum
cmd.Parameters.Add("@ProblemType", SqlDbType.VarChar, 10).Value
= ProblemType

adapter.UpdateCommand = cmd
adapter.Update(datatable)

May 15 '06 #5
Wanddi,

A dataadapter does check if the original datarow is not changed.
(Concurrency checking) Therefore he needs a select as in the sample I gave
you.

A profiler or an executenonquery don't need that select, they just update
it, even if somebody else has changed the data. (Real nice if it is a for a
bank where the money was just taken and now put back or even raised. Don't
try it, this is the most know sample and protected).

I hope I make it clear with this. Have a look at the sample I gave you there
the commands, they are NOT equal to your code.

Cor

"wandii" <wa****@yahoo.com> schreef in bericht
news:11*********************@y43g2000cwc.googlegro ups.com...
Cor,
I tried another simple block of codes, but still not updating the
database and doesn't throw an exception. Again if I
use the ExecuteNonQuery() it updates the database. I can see reading
the table in the Sql Profiler, however, no update. Any idea?

Thanks in advace.

--------------------------------------------------------------
' select statement
cmd = New SqlClient.SqlCommand("Select CaseID, UserID from
dbo.CaseToClose", consql)
adapter.SelectCommand = cmd
adapter.Fill(datatable)

' update statment
cmd = New SqlClient.SqlCommand(" UPDATE dbo.CaseToClose set
DateCompleted = Null, StatusID = 3 " +_
" WHERE CaseID = @CaseID" + _
" AND ProblemTypeID =
@ProblemType ", consql)

cmd.Parameters.Add("@CaseID", SqlDbType.VarChar, 10).Value =
sCaseNum
cmd.Parameters.Add("@ProblemType", SqlDbType.VarChar, 10).Value
= ProblemType

adapter.UpdateCommand = cmd
adapter.Update(datatable)

May 15 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Jim in Arizona | last post by:
I'm doing my best to learn ASPNET from a book devoted to ASPNET 1.0. So far, I haven't run into any problems, until now. This is a simple page that should just show the sql strings created by the...
2
by: susan.f.barrett | last post by:
Hi, Despite me being able to type the following in to SQL Server and it updating 1 row: > updatestockcategory 1093, 839 In my code, it is not updating any rows. dataSet = new DataSet();
1
by: Rich | last post by:
Hello, I can update a dataset from my client app using a dataAdapter.Updatecommand when I add parameter values outside of the param declaration. But If I add the param values inline with the...
6
by: Rich | last post by:
Dim da As New SqlDataAdapter("Select * from tbl1", conn) dim tblx As New DataTable da.Fill(tblx) '--works OK up to this point da.UpdateCommand = New SqlCommand da.UpdateCommand.Connection =...
0
by: stuart_dent | last post by:
I have a SQL Server table with in Indetity column (value auto generated). I have tried to write my own updatecommand code. I can't get it to work. An error says that says Sku and rid are...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.