I have an vb.net application which use the mysql for database.
I am facing a problem which is the result of query is always empty.
Below are my codes.
Protected Sub btnCheck_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCheck.Click
Dim con As String = ConfigurationManager.ConnectionStrings("prcConnectionString").ConnectionString
Dim Sql As New MySqlConnection(con)
Dim reader2 As Object
Sql.Open()
Dim theQuery2 As String = "Select max(shipmentdate) from prc.tbsrparts t where Substring(partsn, 17, 11) =' " & tbPartSN.Text.Substring(16, 11) & "' " 'get latest shipment date from database
Dim command2 As New MySqlCommand(theQuery2, Sql)
reader2 = command2.ExecuteScalar
lbl90days.Text = reader2.ToString
End Sub
The result should be shown at label lbl90days.
But mine is always empty.
Can anyone guide me?
Thanks in advance.
Try this :
Protected Sub btnCheck_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCheck.Click
Dim con As String = ConfigurationManager.ConnectionStrings("prcConnectionString").ConnectionString
Dim Sql As New MySqlConnection(con)
Dim reader2 As Object
Sql.Open()
Dim theQuery2 As String = "Select max(shipmentdate) from prc.tbsrparts t where Substring(partsn, 16, 11) = #PartSN"
Dim command2 As New MySqlCommand(theQuery2, Sql)
command2.CommandType = CommandType.Text
command2.Parameters.AddWithValue("#PartSN", tbPartSN.Text.Substring(16, 11))
reader2 = command2.ExecuteScalar
lbl90days.Text = reader2.ToString
Sql.close()
End Sub
Able to solve by
Dim PartSN As String = tbPartSN.Text.Substring(16, 11)
And replace theQuery2 code with
Dim theQuery2 As String = "SELECT Max(shipmentdate) FROM prc.tbsrparts t WHERE Substring(partsn, 17, 11) = '" + PartSN.ToString + "'"
Related
I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using
I am looking for a way to select columns with a not null property and store it on to an ArrayList.
I have searched many threads for an answer but no luck.
I created a function which allows me to read data from a table but the problem is I don't know how do I get it to read the column name with a not null property. Here is the code that I tried
Public Function getNull(ByVal table As String) As ArrayList
Dim col_names As String = New String(getNames(table))
Dim nullColumns As ArrayList = New ArrayList
Dim dtreader As MySqlDataReader
Dim conn As MySqlConnection
Dim strConn As String
strConn = withDatabase
conn = New MySqlConnection(strConn)
Try
Dim cmd = New MySqlCommand("SELECT * FROM " & table & " WHERE " & col_names & " IS NOT NULL", conn)
conn.Open()
dtreader = cmd.ExecuteReader()
While dtreader.Read
'Get column names with not null property'
End While
Catch ex As Exception
MsgBox("Error " + ex.ToString, MsgBoxStyle.Critical)
End Try
Return nullColumns
End Function
Public Function getNames(ByVal table As String) As String
Dim conn As MySqlConnection
Dim strConn As String
Dim names As New String("")
strConn = withDatabase
conn = New MySqlConnection(strConn)
Using conn
conn.Open()
Dim dt = conn.GetSchema("Columns", New String() {Nothing, Nothing, table})
For Each row In dt.Rows
names += row("COLUMN_NAME") + " AND "
Next
names = names.Remove(names.Length - 4)
End Using
conn.Close()
Return names
End Function
The other threads I found was to find null values in a column, which is not I was looking for.
Hello Everyone Good Afternoon,
I have an Object in a form and they are Datagridview1 and a Save Button the Datagridview1 will populate data from my Database on Form_Load and the Data will show with a Corresponding Checkbox. Like the Image below
and If you here is the code for that
Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)
Here is my code but its not working. :(
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
End Sub
TYSM For future help
Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
name = Me.DataGridView1.Rows(i).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
End If
Next
Imports MySql.Data.MySqlClient
Public Class home1
Dim id As String
Dim name1 As String
Dim name2 As String
Dim address As String
Dim age As Integer
Dim gender As String
Dim bday As Date
Dim height1 As String
Dim weight1 As String
Dim crimcase As String
Dim eye As String
Dim con As New MySqlConnection
Dim source1 As New BindingSource()
Dim source2 As New BindingSource()
Dim ds As DataSet = New DataSet
Dim tables As DataTableCollection = ds.Tables
Private Sub home1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = "Server=localhost;User Id=root;Password='';Database=db_criminalrecord"
Catch ex As Exception
MsgBox(ex.Message)
End Try
fill()
End Sub
Public Sub fill()
Dim dt As New DataTable
Dim str As String = "SELECT ID,Criminal_Name,Alias,Address,Age,Gender,Height,Weight,Date_of_Birth,criminal_Case,Eye_Colour "
Dim da As New MySqlDataAdapter(str, con)
da.Fill(dt)
da.Dispose()
source1.DataSource = dt
DataGridView1.DataSource = dt
DataGridView1.Refresh()
DataGridView1.Columns(13).Width = 150
End Sub
Sub clear()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
TextBox9.Text = ""
TextBox10.Text = ""
End Sub
End Class
Your select statement is not containing FROM TABLE_NAME part.
Imports System.Data.SqlClient
Public Class Form3
Private cs As New SqlConnection("Data Source=HUSAIN-PC;Initial
Catalog=final1;Integrated Security=True")
Private da As New SqlDataAdapter
Private ds As New DataSet
Public dr As SqlDataReader
Public cmd As New SqlCommand
Private sql As String
Private sqlsel As String
Dim Bal As String
Dim id As String
Dim amt As String
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cs.Open()
cmd.Connection = cs
amt = TextBox2.Text
id = TextBox1.Text
sqlsel = "SELECT (Bal) FROM db5 WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sqlsel, cs)
dr = cmd.ExecuteReader
If dr.HasRows = True Then
While (dr.Read())
Bal = dr("Id")
End While
End If
dr.Close()
MessageBox.Show("Balance is :" + Bal)
Dim total As String = Bal + amt
sql = "UPDATE db5 SET Bal='" + total + "' WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sql, cs)
da.InsertCommand.ExecuteNonQuery()
MessageBox.Show("updated")
End Sub
End Class
This is my VB code to retrieve a value from the SQL DB...the Update statement is running fine bt wen i write the select i get an exception in the code:
dr=cmd.ExecuteReader
"ExecuteReader: CommandText property has not been initialized"
Look at this code:
sqlsel = "SELECT (Bal) FROM db5 WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sqlsel, cs)
dr = cmd.ExecuteReader
You're specifying an InsertCommand as a SELECT query, but then you're calling ExecuteReader on a completely separate SqlDataReader... which hasn't got a query configured, as per the error message.
That's why you're getting this specific error, but there are lots of problems with this code:
You should be creating a new SqlConnection / SqlCommand etc every time you want to execute a query
You should be using Using statements to automatically close them
You shouldn't have instance variables for these - they should be local variables
I see no reason to use a DataAdapter here in the first place - just use SqlCommand.ExecuteNonQuery
Very important: You should be using parameterized SQL instead of including values directly in your SQL. See the Bobby Tables site for more information about this topic.