Update statment using vb.net to update all fields - sql

I create table using sql developer
create table tablenodes
(
nodeNo int ,
nodeName varchar2(50),
centerX int ,
centerY int,
radius number(7,2),
fileNo int
)
And I want to update all fields in this table, so I wrote the following code:
Friend Function UpdateNodeToTable(ByVal FN As Integer, ByVal nd As classNode) As Boolean
Try
Dim con As New OracleConnection
con.ConnectionString = "Persist Security Info=False;User ID=manal;password=manal;Data Source=xe"
con.Open()
Dim cmd As New OracleCommand
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.CommandText = "update tablenodes set nodeName=#NodeName, centerX = #NodeCenterX," & _
"centerY= #NodeCenterY , radius= #NodeRadius where nodeNo= #nodeNum and fileno= #FileNum"
cmd.Parameters.Add("#NodeNum", OracleDbType.Int32).Value = nd.pID
cmd.Parameters.Add("#NodeName", OracleDbType.Varchar2).Value = nd.pName
cmd.Parameters.Add("#NodeCenterX", OracleDbType.Int32).Value = nd.pCenter.X
cmd.Parameters.Add("#NodeCenterY", OracleDbType.Int32).Value = nd.pCenter.Y
cmd.Parameters.Add("#NodeRadius", OracleDbType.Double).Value = nd.pRadius
cmd.Parameters.Add("#FileNum", OracleDbType.Int32).Value = FN
Dim success As Boolean
If cmd.ExecuteNonQuery() = 1 Then
success = True
Else
success = False
End If
cmd.Dispose()
con.Close()
con.Dispose()
Return success
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function
I have a problem in updating statements, can't write it correctly, every time I try to edit it, gives me different error (ora-01036 illegal variable name/number, missing expression, invalid identifier).

The bind variables in you UPDATE statement should be prefixed by a colon, not the # symbol
cmd.CommandText = "update tablenodes set nodeName=:NodeName, centerX = :NodeCenterX," & _
"centerY= :NodeCenterY , radius= :NodeRadius where nodeNo= :nodeNum and fileno= :FileNum"
And there would be no prefix what you're setting the parameters
cmd.Parameters.Add("NodeNum", OracleDbType.Int32).Value = nd.pID
cmd.Parameters.Add("NodeName", OracleDbType.Varchar2).Value = nd.pName
cmd.Parameters.Add("NodeCenterX", OracleDbType.Int32).Value = nd.pCenter.X
cmd.Parameters.Add("NodeCenterY", OracleDbType.Int32).Value = nd.pCenter.Y
cmd.Parameters.Add("NodeRadius", OracleDbType.Double).Value = nd.pRadius
cmd.Parameters.Add("FileNum", OracleDbType.Int32).Value = FN

Related

Executing a stored procedure in vb

I'm using the current code to try to execute a stored procedure, and it shows no errors, but the update made by the procedure is not executed.
Public Function UpdateRouteByRegister(ByVal conexion As String, ByVal idRegister As Integer, ByVal route As String) As Boolean
Try
ConnectionString = conexion
myConnection = New SqlConnection(ConnectionString)
myDataAdapter = New SqlDataAdapter("spUpdateHistoricLoad", myConnection)
myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
myDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("#idRegister", SqlDbType.Int))
myDataAdapter.SelectCommand.Parameters("#idRegister").Value = idRegister
myDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("#route", SqlDbType.VarChar, 100))
myDataAdapter.SelectCommand.Parameters("#route").Value = route
myDataAdapter.SelectCommand.CommandTimeout = 0
myDataset = New DataSet
myDataAdapter.Fill(myDataset)
myDataset.Dispose()
myConnection.Close()
Log("******* Register updated = " + idRegister.ToString + " *******")
Return True
Catch objException As Exception
Log("******* Error on updating register = " + idRegister.ToString + " *******")
Return False
End Try
End Function
The SQL Stored Procedure is the following:
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUpdateHistoricLoad]
#idRegister INTEGER,
#route VARCHAR(100)
AS
BEGIN
UPDATE tOperation SET ImagenMulti = #route WHERE IDRegister = #idRegister
END
I would suggest dropping the DataAdapter and DataSet objects and just use a SqlCommand:
Public Function UpdateRouteByRegister(ByVal conexion As String, ByVal idRegister As Integer, ByVal route As String) As Boolean
Try
ConnectionString = conexion
myConnection = New SqlConnection(ConnectionString)
myConnection.Open
Dim cmd as SqlCommand
cmd = New SqlCommand("spUpdateHistoricLoad", myConnection)
cmd.Parameters.AddWithValue("#idRegister", idRegister)
cmd.Parameters.AddWithValue("#route", route)
cmd.CommandTimeout = 0
cmd.ExecuteNonQuery
myConnection.Close()
Log("******* Register updated = " + idRegister.ToString + " *******")
Return True
Catch objException As Exception
Log("******* Error on updating register = " + idRegister.ToString + " *******")
Return False
End Try
End Function

Must declare the scalar variable "#Modifier"

I have been trying to figure out what I am doing wrong for a few hours now. I am trying to add a record to my database but I am not able to do so because of the error I am getting that reads "Must declare the scalar variable "#Modifier"." I noticed other people with similar issues but I couldn't apply the same fixes to my code.
Dim dbConnection As SqlConnection = connectToDb()
Dim sqlString As String
If currentWeapon.Id > 0 Then
sqlString = "Update Weapons Set Name = #name"
Else
sqlString = "INSERT INTO Weapons (Name, APPower, HEPower, Range, Modifier) VALUES(#name, #APPower, #HEPower, #Range, #Modifier)"
lastWeaponId += 1
currentWeapon.Id = lastWeaponId
End If
Dim com As New SqlCommand(sqlString, dbConnection)
com.Parameters.Add("#name", SqlDbType.VarChar).Value = currentWeapon.Name
com.Parameters.Add("#APPower", SqlDbType.Int).Value = currentWeapon.APPower
com.Parameters.Add("#HEPower", SqlDbType.Int).Value = currentWeapon.HEPower
com.Parameters.Add("#Range", SqlDbType.Int).Value = currentWeapon.Range
com.Parameters.Add("#Modifer", SqlDbType.VarChar).Value = currentWeapon.Modifier
Try
Dim result = com.ExecuteNonQuery()
MessageBox.Show(result.ToString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
You wrote #Modifer instead of #Modifier
com.Parameters.Add("#Modifer", SqlDbType.VarChar).Value = currentWeapon.Modifier
^
You have a typo: #Modifer vs. #Modifier.
In your query, you use #Modifier:
"INSERT INTO Weapons (Name, APPower, HEPower, Range, Modifier)
VALUES(#name, #APPower, #HEPower, #Range, #Modifier)"
But you specify the parameter name on the command as #Modifer:
com.Parameters.Add("#Modifer", SqlDbType.VarChar).Value = currentWeapon.Modifier

SQL parameter either integer value or dbnull pass to query

Can't get my query to work. I want to pass either integer value or dbnull to my query but in that form is not working. Below my code.
Query:
Using cmd As New SqlCommand("SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = #FK_Sentence_Id And FK_SubSection_Id = #FK_SubSection_Id And FK_SubSubKategorie_Id=#FK_SubSubKategorie_Id", con)
Parameter set up based on which one i need:
If _FK_SubSubKategorie_Id = 0 Then
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", DBNull.Value)
Else
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", _FK_SubSubKategorie_Id)
End If
if _FK_SubSubKategorie_Id is set to DBNull as shown my query should change a bit instead this part:
And FK_SubSubKategorie_Id=#FK_SubSubKategorie_Id", con)
to
And FK_SubSubKategorie_Id IS NULL", con)
What is the right way to do?
that's entire SQL function:
#Region "Check if connection already exist"
Public Function CheckIfConnectionAlreadyExist(_FK_Sentence_Id As Integer, _FK_SubSection_Id As Integer, _FK_SubSubKategorie_Id As Integer) As Boolean
Dim result As Boolean
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(String)).ToString()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand("SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = #FK_Sentence_Id And FK_SubSection_Id = #FK_SubSection_Id And FK_SubSubKategorie_Id=#FK_SubSubKategorie_Id", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#FK_Sentence_Id", _FK_Sentence_Id)
cmd.Parameters.AddWithValue("#FK_SubSection_Id", _FK_SubSection_Id)
If _FK_SubSubKategorie_Id = 0 Then
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", DBNull.Value)
Else
cmd.Parameters.AddWithValue("#FK_SubSubKategorie_Id", _FK_SubSubKategorie_Id)
End If
con.Open()
Dim o As Integer = cmd.ExecuteScalar()
If o > 0 Then
result = True
Else
result = False
End If
con.Close()
End Using
End Using
Return result
End Function
#End Region
Just create one query string which both conditions have in common and change it regarding _FK_SubSubKategorie_Id afterwards. Then create the command:
Dim qry as String = "SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = #FK_Sentence_Id And FK_SubSection_Id = #FK_SubSection_Id And FK_SubSubKategorie_Id {0}"
If _FK_SubSubKategorie_Id = 0 Then
qry = string.Format(qry," IS NULL")
Else
qry = string.Format(qry, "=#FK_SubSubKategorie_Id"
End if
Using cmd As New SqlCommand(qry, con)
...

fetching data from SQL server and print it out using loop

I'm trying to fetch all the data rows in a sql server to print all the values. Here is the code I already tried but it still does not work. Can someone tell me what is wrong here? I'm quite new to vb.net
For i = 1 To 100
Dim testsection As String = e.Item.DataItem("sectionName")
e.Item.Cells(4).Text = strSection & testsection
Next
i dont quite understand how it fetch the data. i juz work as a fresh grad. but they already assign me this advance task. here is the codes in my DBFunction.
Public Function GetUserList(ByVal strUserLogin As String, ByVal strName As String, _
ByVal intCompanyID As Integer, ByVal tblName As String) As DataSet
Dim oConn As SqlConnection = Nothing
Dim SQLStr As String = ""
Dim SubSQL As String = ""
Dim CMD As SqlCommand = Nothing
Dim DS As New DataSet
Dim DA As New SqlDataAdapter
Try
oConn = New SqlConnection(ConnectionString)
oConn.ConnectionString = ConnectionString
oConn.Open()
CMD = oConn.CreateCommand
CMD.CommandType = CommandType.StoredProcedure
SQLStr = "sp_tblUser_Get"
'CMD.Parameters.Add("#CompanyID", SqlDbType.Int).Value = intCompanyID
CMD.Parameters.Add("#LoginID", SqlDbType.VarChar, 50).Value = strUserLogin
CMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = strName
'If strUserLogin <> "" Then
' SubSQL = " AND u.UserLogin = " & SQLS(strUserLogin)
'End If
'If intCompanyID <> 0 Then
' SubSQL = " AND u.CompanyId = " & SQLN(intCompanyID)
'End If
'SQLStr = "select u.ID, u.UserLogin, u.Name, c.CompanyName, u.CreateDate from tblUser u " & _
' " inner join tblCompany c on u.CompanyId = c.ID WHERE u.ID <> 0 " & SubSQL
CMD.CommandText = SQLStr
DA.SelectCommand = CMD
DA.Fill(DS, tblName)
CMD = Nothing
DA = Nothing
oConn.Close()
oConn = Nothing
Catch ex As System.Exception
DS = Nothing
Finally
If Not oConn Is Nothing Then
oConn.Close()
oConn = Nothing
End If
If Not CMD Is Nothing Then
CMD = Nothing
End If
End Try
Return DS
End Function
Basically lines from Dim oConn As SqlConnection = Nothing to DA.SelectCommand = CMD are used to create connection with the database and have steps to call procedure having name sp_tblUser_Get.
Then all the required parameters of this procedure are paased using lines
CMD.Parameters.Add("#LoginID", SqlDbType.VarChar, 50).Value = strUserLogin
CMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = strName
After that using SqlDataAdapter's Fill method data set is filled with the out put.
Dataset DS can contain single DataTable or multiple Datatables which depends on hot Stored procedure is written.
I am assuming it contains single datatable, then if you want to view data then in you can use.
DataTable dt= DS.Tables[0];
This dt Datatablw will contain all data.
To display that data you can use loop like mentioned below.
DataTable dt = DS.Tables[0];
foreach (DataRow dr in dt.Rows)
{
String Name = dr["FirstName"].ToString();
int Age = Convert.ToInt32(dr["Age"]);
}

Insert and Select at the same time in a stored procedure

I have the following stored procedure:
create procedure Insert_Maintenance
(
#PlateNo nvarchar(10),
#MaintenanceType nvarchar(150),
#Name nvarchar(300),
#MaintenanceDate date,
#Qty int,
#IndivisualVal float,
#TotalVal float,
#Notes nvarchar(300)
)
as
insert into Maintenance(MaintenanceNo, PlateNo, MaintenanceType, AutoCenterNo,MaintenanceDate, Qty, IndivisualVal, TotalVal, Notes)
values ((1+(select Max(MaintenanceNo) from Maintenance)), #PlateNo, #MaintenanceType, (select AutoCenterNo from AutoCenter where Name = #Name), #MaintenanceDate, #Qty, #IndivisualVal, #TotalVal, #Notes)
Select Max(MaintenanceNo) AS MNo from Maintenance
A user will insert new maintenance operation via VB.NET interface. The information of the maintenance will be inserted into the database. The ID of the maintenance will increase by 1; as it is shown in the code. Since this is the case, after inserting the information I want to show a message that tells the user that information entered correctly and the ID of this operation is the value of MNo.
Basically, the problem is not with the VB.NET code because the message works fine but the problem is related to the select statement that shows the maintenance ID to the user.
The code in VB.NET
Dim ConnectString As String
ConnectString = ""
Dim connection As New SqlConnection(ConnectString)
'Dim parm1 As SqlParameter
'parm1 = New SqlParameter("#MaintenanceNo", SqlDbType.Int)
'parm1.Value = MaintenanceNoTextBox.Text
Dim parm2 As SqlParameter
parm2 = New SqlParameter("#PlateNo", SqlDbType.NVarChar)
parm2.Value = PlateNoComboBox.Text
Dim parm3 As SqlParameter
parm3 = New SqlParameter("#MaintenanceType", SqlDbType.NVarChar)
parm3.Value = MaintenanceTypeTextBox.Text
Dim parm4 As SqlParameter
parm4 = New SqlParameter("#Name", SqlDbType.NVarChar)
parm4.Value = NameComboBox.Text
Dim parm5 As SqlParameter
parm5 = New SqlParameter("#MaintenanceDate", SqlDbType.Date)
parm5.Value = MaintenanceDateDateTimePicker.Value
Dim parm6 As SqlParameter
parm6 = New SqlParameter("#Qty", SqlDbType.Int)
parm6.Value = QtyTextBox.Text
Dim parm7 As SqlParameter
parm7 = New SqlParameter("#IndivisualVal", SqlDbType.Float)
parm7.Value = IndivisualValTextBox.Text
Dim parm8 As SqlParameter
parm8 = New SqlParameter("#TotalVal", SqlDbType.Float)
parm8.Value = TotalValTextBox.Text
Dim parm9 As SqlParameter
parm9 = New SqlParameter("#Notes", SqlDbType.NVarChar)
parm9.Value = NotesTextBox.Text
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = connection
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Insert_Maintenance"
'cmd.Parameters.Add(parm1)
cmd.Parameters.Add(parm2)
cmd.Parameters.Add(parm3)
cmd.Parameters.Add(parm4)
cmd.Parameters.Add(parm5)
cmd.Parameters.Add(parm6)
cmd.Parameters.Add(parm7)
cmd.Parameters.Add(parm8)
cmd.Parameters.Add(parm9)
Try
connection.Open()
cmd.ExecuteNonQuery()
Dim dreader As SqlDataReader
dreader = cmd.ExecuteReader()
Dim a As String
a = dreader("MNo").ToString
MessageBox.Show("Information entered, ID is " + a)
dreader.Close()
'MaintenanceNoTextBox.Text = ""
PlateNoComboBox.Text = ""
MaintenanceTypeTextBox.Text = ""
NameComboBox.Text = ""
'MaintenanceDateDateTimePicker.Value = ""
QtyTextBox.Text = ""
IndivisualValTextBox.Text = ""
TotalValTextBox.Text = ""
NotesTextBox.Text = ""
Catch ex As Exception
MessageBox.Show("Something wrong (" + ex.Message + ")")
Finally
connection.Close()
End Try
Any suggestions guys !! Thanks
To solve your problem you need to just change one line and remove a bunch of unnecessary code
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = connection cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Insert_Maintenance"
.... you need to build the parameters collection here .....
Try
connection.Open()
Dim result = cmd.ExecuteScalar() ' <- Instead of ExecuteNonQuery '
if result IsNot Nothing Then
Console.WriteLine("The Mno is:" & Convert.ToInt32(result)
End If
ExecuteScalar returns the first column of the first row in your results. This should resolve the VB.NET side of your code. Of course, if you don't need to control the values inserted in the column MaintenanceNo then the next action to take is to set the Identity property to Yes in the field properties. In this way you could remove the last lines of your storedprocedure and forget to pass anything for the MaintenaceNo field
INSERT INTO Maintenance(PlateNo, MaintenanceType, AutoCenterNo,MaintenanceDate, Qty,
IndivisualVal, TotalVal, Notes)
VALUES (#PlateNo, #MaintenanceType,
(select AutoCenterNo from AutoCenter where Name = #Name),
#MaintenanceDate, #Qty, #IndivisualVal, #TotalVal, #Notes)
SELECT SCOPE_IDENTITY()
I think ID of Maintainance table should be auto-increment. For achieving that you can set Is Identity to Yes
In the end of insert if you want the ID than you can get by
Select SCOPE_IDENTITY()
If you want to increment ID manually then try this :
declare #newid int
Select #newid = Max(ISNULL(MaintenanceNo, 0)) from Maintenance
set #newid = #newid + 1
then use #newid for insert and in the end Select #newid