SQL parameter either integer value or dbnull pass to query - vb.net

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)
...

Related

I want a quick solution about adding a new row to datagraidview

I have a DataGridView and I'm adding a new row. But, when I add the new row it deletes the current row and replaces it.
This is the code
Try
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("SELECT ItemID, RTRIM(DishName),'1',Rate from Dish where ItemID like '" & TextBox1.Text & "' order by DishName", con)
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While (rdr.Read() = True)
DataGridView1.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3))
Dim num1 As Double
num1 = Val(DataGridView1.Rows(0).Cells("Qty").Value) * Val(DataGridView1.Rows(0).Cells("Rate").Value)
num1 = Math.Round(num1, 2)
DataGridView1.Rows(0).Cells("Amount").Value = num1
End While
TotalCalc()
Compute()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I am having a little problem following your question
Suggestion Don't tell us you want a quick solution
If you are changing the value in the DB use Update
Here is some code to add values to a DataGridView with SQLite
The SELECT statement is a little odd due to another issue in my Project
Just use your SELECT also Welcome to Stackoverflow
Private Sub ViewSearches()
Dim intID As Integer
Dim strCodeDesc As String
Dim strUIProject As String
Dim strCodeType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
If gvTxType = "View" Then
cmd.CommandText = "SELECT * FROM CodeTable WHERE cvCodeType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSCT
ElseIf gvTxType = "All" Then
cmd.CommandText = "SELECT * FROM CodeTable"
End If
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
While rdr.Read()
intID = CInt((rdr("CID")))
strCodeDesc = rdr("cvCodeDesc").ToString
strUIProject = rdr("cvUIProject").ToString
strCodeType = rdr("cvCodeType").ToString
dgvSelCode.Rows.Add(intID, strCodeDesc, strUIProject, strCodeType)
rowCount += 1
End While
dgvSelCode.Sort(dgvSelCode.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 12 Then
maxRowCount = 12 - rowCount
For iA = 1 To maxRowCount
dgvSelCode.Rows.Add(" ")
Next
End If
End Using
End Using
End Sub

Insert data from VB net into Postgresql

I'm trying to input data from my vb into PostgreSQL
the source is another database on Ms Access
im using this code for connection
Public Function LoadAcces_tblpibconr() As DataTable 'ganti ini sesuai nama table
Dim Table As DataTable = New DataTable()
Command.Connection = conn.OpenConnection()
Command.CommandText = "select * from tblpibconr"
Command.CommandType = CommandType.Text
ReadRows = Command.ExecuteReader()
Table.Load(ReadRows)
ReadRows.Close()
conn.CloseConexion()
Return Table
End Function
'=====================================TABLE POSTGRESQL========================='
Public Function LoadNpgsql_tblpibconr() As DataTable
Dim Table As DataTable = New DataTable()
Cmd.Connection = connNpgsql.OpenConnection()
Cmd.CommandText = "select * from tblpibconr"
Cmd.CommandType = CommandType.Text
ReadRows1 = Cmd.ExecuteReader()
Table.Load(ReadRows1)
ReadRows1.Close()
connNpgsql.CloseConexion()
Return Table
End Function
I'm using this function for filtering the data
I'll compare the data first and take the data without a match and stored it into postgresql
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
Dim Table As DataTable = New DataTable()
Cmd.Connection = connNpgsql.OpenConnection()
If Cmd.Parameters.Count > 0 Then
Cmd.Parameters.Clear()
End If
Cmd.Parameters.AddWithValue("#car", car)
Cmd.Parameters.AddWithValue("#reskd", reskd)
Cmd.Parameters.AddWithValue("#contno", contno)
Cmd.CommandText = <sql>select * from tblpibconr where car=#car and reskd=#reskd and contno=#contno</sql>.Value
Cmd.CommandType = CommandType.Text
ReadRows1 = Cmd.ExecuteReader() 'ERROR System.InvalidOperationException: 'Parameter '#car' must have its value set'
Table.Load(ReadRows1)
ReadRows1.Close()
If Table.Rows.Count > 0 Then
Return False
Else
Return True
End If
Cmd.Parameters.Clear()
connNpgsql.CloseConexion()
End Function
Sub bandingkan_data_tblpibconr()
For i = 0 To DGV1.Rows.Count - 1
Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) 'cek data dari access ke postgresql
If validasi = True Then 'jika data di access tidaj ada
'inser data
Dim a As String
If IsDBNull(DGV1.Rows(i).Cells(4).Value.ToString()) Then
a = "0"
Else
a = DGV1.Rows(i).Cells(4).Value.ToString()
End If
DGV1.Rows(i).DefaultCellStyle.BackColor = Color.MistyRose
Dim Insertdata = query.insertNpgsql_tblpibconr(DGV1.Rows(i).Cells(0).Value.ToString(), DGV1.Rows(i).Cells(1).Value.ToString(), DGV1.Rows(i).Cells(2).Value.ToString() _
, DGV1.Rows(i).Cells(3).Value.ToString(), a)
If Insertdata = True Then
' MsgBox("Masuk")
Else
MsgBox("Data Gagal DIMASUKAN")
End If
End If
Next i
LoadNpgsql_tblpibconr()
MsgBox("Selesai")
End Sub
Public Function insertNpgsql_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String, ByVal contukur As String, ByVal conttipe As String) As Boolean
Cmd.Connection = connNpgsql.OpenConnection()
If Cmd.Parameters.Count = 0 Then
Cmd.Parameters.Clear()
End If
Try
Cmd.CommandText = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(#car,#reskd,#contno,#contukur,#conttipe)"
Cmd.CommandType = CommandType.Text
Cmd.Parameters.AddWithValue("#car", car)
Cmd.Parameters.AddWithValue("#reskd", reskd)
Cmd.Parameters.AddWithValue("#contno", contno)
Cmd.Parameters.AddWithValue("#contukur", contukur)
Cmd.Parameters.AddWithValue("#conttipe", conttipe)
Cmd.ExecuteNonQuery()
str = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(#car , #reskd , #contno, #contukur, #conttipe)"
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
connNpgsql.CloseConexion()
End Function
this is the error that I get
System.InvalidOperationException: 'Parameter '#car' must have its
value set'
ITS Refer to ReadRows1 = Cmd.ExecuteReader() on function cekdata_tblpibconr and Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) on sub bandingkan_data_tblpibconr
but this error appear after the data successfully inserted to my Postgresql
Before running the Function where the error occurred, I have checked if we really have a value for car.
This method demonstrates what I mean by keeping your database objects local. The connection and command are created locally in a Using block. They will be closed and disposed even it there is an error.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the command text and the connection to the constructor of the command. The default CommandType is CommandType.Text so it is not necessary to explicitly set that property.
Open the connection at the last possible moment directly before the command is executed.
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
If String.IsNullOrEmpty(car) Then
MessageBox.Show("Car has no value")
Return True '??
End If
Dim Table As DataTable = New DataTable()
Using cn As New NpgsqlConnection(ConStr),
cmd As New NpgsqlCommand("select * from tblpibconr where car=#car and reskd=#reskd and contno=#contno;", cn)
cmd.Parameters.Add("#car", NpgsqlDbType.Varchar).Value = car
cmd.Parameters.Add("#reskd", NpgsqlDbType.Varchar).Value = reskd
cmd.Parameters.Add("#contno", NpgsqlDbType.Varchar).Value = contno
cn.Open()
Table.Load(cmd.ExecuteReader)
End Using
If Table.Rows.Count > 0 Then
Return False
Else
Return True
End If
End Function

How to execute query and store data of a column in a variable in VB.net?

I have the following code where I am trying to execute a query and store the value from the database in two variables. Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Here is the code:
Try
Dim cn As SqlConnection
Dim strCnn As String = ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString
cn = New SqlConnection(strCnn)
cn.Open()
Dim comm As New SqlCommand("select IsCompleted, CompletionDate from managerchecklist where ID = 53 and QuestionID = 1", cn)
comm.CommandType = CommandType.Text
Dim ds As SqlDataReader
ds = comm.ExecuteReader()
If ds.HasRows Then
While ds.Read
IsComplete = ds.Item("IsCompleted").ToString()
CompleteDate = ds.Item("CompletionDate").ToString()
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End While
End If
''Close your connections and commands.
cn.Close()
Catch ex As Exception
''Handle error if any
End Try
But I seem to be going wrong somewhere. Can anyone please help me?
Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Have an If Statement to check the variables whether it is complete
If IsComplete = "complete" Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End If
Move the checking to SQL statement
Dim comm As New SqlCommand(
"select IsCompleted, CompletionDate from " +
"managerchecklist where ID = 53 and QuestionID = 1 and "
"IsCompleted = 'complete'",
cn)
Consider using parameter SQL instead to prevent SQL injection
I would recommend a Using statement for SQL queries and also parameters.
Get the values from SQL then use an IF statement to do whatever based on the values.
Assuming IsCompleted is a bit field in SQL....
Dim isCompleted As Boolean
Dim completedDate As Date
Using con As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString)
Using cmd As New SqlClient.SqlCommand("SELECT [IsCompleted], [CompletionDate] FROM managerchecklist where [ID] = #managerchecklistID and [QuestionID] = #questionID", con)
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = 53
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = 1
con.Open()
Using reader As SqlClient.SqlDataReader = cmd.ExecuteReader
While reader.Read
'Index in order of the columns in the SELECT statement
If reader.GetSqlBoolean(0).IsNull = False Then isCompleted = reader.GetSqlBoolean(0)
If reader.GetSqlDateTime(1).IsNull = False Then completedDate = reader.GetSqlDateTime(1)
End While
End Using
End Using
End Using
If isCompleted Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = completedDate
End If
You could place this in a Sub of it's own with managerchecklistID and questionID as arguments then set the parameter values with the arguments
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = managerchecklistID
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = questionID

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

need to get value from sql query

Through ADO,I like to do the following query:
select name, address, zip from terr where id = '33334'
I like then to assign name, addess, zip to variables so that I can assign it later in my program.
How do I do this with VB.NET ADO?
Try somethign like this:
Dim dbName As String
Dim dbAddress As String
Dim dbZip As String
Using connObj As New SqlClient.SqlConnection("<connectionString>")
Using cmdObj As New SqlClient.SqlCommand("select name, address, zip from terr where id = '33334'", connObj)
connObj.Open()
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
'This will loop through all returned records
While readerObj.Read
dbName = readerObj("name").ToString
dbAddress = readerObj("address").ToString
dbZip = readerObj("zip").ToString
'handle returned value before next loop here
End While
End Using
connObj.Close()
End Using
End Using
Also, you should look into parameterizing the value for the where clause.
You need a DataBase (i assume MS Sql-Server), a Connection and a DataAdapter to fill a DataTable. Then you have all you need. Here's an example:
Public Function GetUser(UserId As Int32) As DataRow
Using con = New SqlConnection(My.Settings.RM2ConnectionString)
Using cmd = New SqlCommand("select name, address, zip from terr where id = #id", con)
cmd.Parameters.AddWithValue("#id", UserId)
Dim da = New SqlDataAdapter(cmd)
Dim tblUser = New DataTable
da.Fill(tblUser)
If tblUser.Rows.Count <> 0 Then
Return tblUser(0)
Else
Return Nothing
End If
End Using
End Using
End Function
execute a SqlCommand from SQLDatareader, like:
Dim vVendedor As New SqlCommand("SELECT user FROM users", mConeccion)
vDatosVen = vVendedor.ExecuteReader
vVendedor = Nothing
and to get te value:
While vDatosVen.Read()
vUser = vDatosVen("user")
End While
Here's what i did...
Private Sub btn_Connect_Click(sender As Object, e As EventArgs) Handles btn_Connect.Click
Dim sql_connection As New MySqlConnection
Dim sql_query As New MySqlCommand
Dim sql_result As MySqlDataReader
sql_connection.ConnectionString = "Server=localhost;Database=hidden;Uid=root;Pwd=;"
sql_query.Connection = sql_connection
sql_connection.Open()
sql_query.CommandText = "SELECT Entry,name FROM table WHERE entry=1;"
sql_result = sql_query.ExecuteReader
If sql_result.HasRows Then
Do While sql_result.Read()
Dim query_result As String
query_result = sql_result("name")
MsgBox(query_result)
Loop
Else
MsgBox("No results found.")
End If