My code is :
Dim c3 As MySqlCommand
Dim q3 As String = "SELECT date
FROM `river-derwent-keswick-portinscale`
WHERE(`date` = Input)"
c3 = New MySqlCommand(q3, conn)
'c3.Parameters.AddWithValue("#Date", Userinput.Text)
'Userinput.Text Is a textbox
' If a field if found where the date matches the userinput
' Output value to textbox
Dim DR3 As MySqlDataReader = c3.ExecuteReader()
If DR3.Read Then
Datetxt.Text = DR3.GetValue(0)
End If
DR3.Close()
This uses a preset constant of a global variable set inside of another form which is Input, where input = textbox1.text. This means a user would input a value into textbox1.text then that value is set as Input. Can someone help me in how to use this constant to query with a Where statement.
You almost had it in the commented code. Modify the query to accept a date argument:
SELECT date
FROM `river-derwent-keswick-portinscale`
WHERE(`date` = #date_param)
Then add parameter to the command
c3.Parameters.AddWithValue("#date_param", Userinput.Text)
Dim c3 As MySqlCommand
Dim q3 As String = "SELECT date FROM `river-derwent-keswick-portinscale` WHERE(`date` = #Date)"
c3 = New MySqlCommand(q3, conn)
c3.Parameters.AddWithValue("#Date", Userinput.Text)
'Userinput.Text Is a textbox
' If a field if found where the date matches the userinput
' Output value to textbox
Dim DR3 As MySqlDataReader = c3.ExecuteReader()
If DR3.Read Then
Datetxt.Text = DR3.GetValue(0)
End If
DR3.Close()
Related
My application outputs "System.InvalidCastException: "Object cannot be cast from DBNull to other types."
Dim sqlquery = String.Format("SELECT id, date, film, start_time, end_time, participants_count, confirmed FROM calendar WHERE id='" & id & "'")
connection.Open()
With command
.Connection = connection
.CommandText = sqlquery
End With
dataadapter.SelectCommand = command
dataadapter.Fill(datatable)
id = Convert.ToInt32(datatable.Rows(0).Item("id"))
Dim date_ As String = datatable.Rows(0).Item("date").ToString
Dim film As String = datatable.Rows(0).Item("film").ToString
Dim start_time As String = datatable.Rows(0).Item("start_time").ToString
Dim end_time As String = datatable.Rows(0).Item("end_time").ToString
Dim participants_count As Integer = Convert.ToInt32(datatable.Rows(0).Item("participants_count"))
Dim confirmed As Integer = Convert.ToInt32(datatable.Rows(0).Item("confirmed"))
The problem arises there: "participants_count" and "confirmed". All the other columns are working perfectly. In the database these two columns aren't DBNull: Picture of the real MySQL-Result. They can't even be DBNull: MySQL Structure
If I output the value of both with a MessageBox it also contains nothing.
I would be very grateful if I became a solution.
Julius
Dim participants_count As Integer
Integer.TryParse(datatable.Rows(0).Item("participants_count").Tostring, participants_count)
This will attempt to convert it to an Integer and returns 0 if it fails otherwise it will set the value to participants_count. This should help with the DBNull issue. You can do this with the confirmed field to.
You can get the query results without using a DataTable. That way you can be exact about the data types and so there is less chance of something unexpected happening:
Dim connStr = "your connection string"
Dim sql = "SELECT `id`, `date`, `film`, `start_time`, `end_time`, `participants_count`, `confirmed` FROM `calendar` WHERE `id` = #id"
Dim id = "2"
Dim date_ As DateTime
Dim start_time As TimeSpan
Dim end_time As TimeSpan
Dim participants_count As Integer
Dim confirmed As Boolean
Using conn As New MySqlConnection(connStr)
Using cmd As New MySqlCommand(sql, conn)
cmd.Parameters.Add(New MySqlParameter With {
.ParameterName = "#id",
.MySqlDbType = MySqlDbType.VarChar,
.Size = 8,
.Value = id})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
date_ = rdr.GetDateTime(1)
start_time = rdr.GetTimeSpan(3)
end_time = rdr.GetTimeSpan(4)
participants_count = rdr.GetInt16(5)
confirmed = rdr.GetBoolean(6)
End If
conn.Close()
End Using
End Using
The SQL parameter should have its .MySqlDbType and .Size set to match the id column in the database. The rdr.Get... functions should be chosen to match the types from the database.
I will explain this as much as possible.
I have a project which need to show the names from database to textboxes. I have 2 datetimepicker for searching between dates and 5 textboxes to show the names in mysql database. for example I select the from start date 2018/12/07 and end date 2019/01/07 in the datagridview it will show all the rows and columns in-between dates. However, I need the names to show on my 5 textboxes. I don't have a code since I don't know where to begin with.
In mysqldatabase I have only id,name,dateofentry.
In my form :
datetimepicker1 = startdate
datetimepicker2 = enddate
button1 = generatebutton
textbox1 = nametxt1
textbox2 = nametxt2
textbox3 = nametxt3
textbox4 = nametxt4
textbox5 = nametxt5
Update when I use this:
mysqlconn.Open()
COMMAND.Connection = mysqlconn
COMMAND.CommandText = "Select name from table1 where dateofentry between '" & Format(Me.startdate.Value, "yyyy-MM-dd") & "' AND '" & Format(Me.endtime.Value, "yyyy-MM-dd") & "'"
Dim sqlresult1 As Object
sqlresult1 = COMMAND.ExecuteScalar
Dim str1 As String
str1 = sqlresult1
nametxt1.Text = str1
mysqlconn.Close()
The same name shows in each of my 5 textboxes
Thank you for answering this question.
Explanations and comments in-line.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'The Using block ensures that your database objects are closed and disposed
'even if there is an error
Dim dt As New DataTable
Using cn As New MySqlConnection("Your connection string")
'Pass the Select statement and the connection to the constructor of the command
Using cmd As New MySqlCommand("Select name from table1 where dateofentry between #Date1 AND #Date2;", cn)
'Use parameters
cmd.Parameters.Add("#Date1", MySqlDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Date2", MySqlDbType.Date).Value = DateTimePicker2.Value
'open the connection at the last possible moment
cn.Open()
'Execute scalar only returns the first row, first column of the result set
dt.Load(cmd.ExecuteReader)
End Using
End Using
'Then a little link magic to dump the first column of the table
'to an array
Dim names() = (From row In dt.AsEnumerable()
Select row(0)).ToArray
'If there are less than 5 records returned this
'code will fail, Add a check for this and
'adjest your code accordingly
TextBox1.Text = names(0).ToString
TextBox2.Text = names(1).ToString
TextBox3.Text = names(2).ToString
TextBox4.Text = names(3).ToString
TextBox5.Text = names(4).ToString
End Sub
SELECT *
FROM `tblPerson`
WHERE (date_field BETWEEN '2018-12-30 14:15:55' AND '2019-01-06 10:15:55')
LIMIT 5;
text1.text = dt.Rows[0]["name"].ToString();
text2.text = dt.Rows[1]["name"].ToString();
text3.text = dt.Rows[2]["name"].ToString();
text4.text = dt.Rows[3]["name"].ToString();
text5.text = dt.Rows[4]["name"].ToString();
I have a SQL VBA query for updating values in several textboxes on a form on the click of a button.
The query takes the input from the multiple label name captions on the form. So caption of Label1 will be input for TextBox1, Label2 caption for Textbox2 etc.
I am trying to pass the label name through a variable to the query. However the following error is returned on the line where value of variable b is generated:
"Microsoft Access can't find the field '&labelname&'referred to in your expression.
My code is below. I want to use a variable so that later I can make it a function to accept the label name and return the recordset value. In this way I will be able to avoid approx. 150 lines of code as I have to update 20 to 25 textboxes with the input from same number of labels.
Private Sub Command111_Click()
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim ssql As String
Dim labelname As String
Dim b As String
Set dbs = CurrentDb
'--------------------------------------------------------------------------- ----
labelname = "Label24"
b = [Forms]![Bal_Sheet]![& labelname &].Caption
ssql = "select sum(a.[Bal Fwd]) from Trial_Balance a,Act_Master b where a.GBOBJ = b.object and a.GBSUB = b.sub and b.Cat = " & "'" & b & "'"
Debug.Print ssql
Set rs = dbs.OpenRecordset(ssql, dbOpenDynaset)
[Forms]![Bal_Sheet]![Text1].Value = rs(0)
'-------------------------------------------------------------------------------
rs.Close
Set rs = Nothing
dbs.Close
End Sub
Your expression:
b = [Forms]![Bal_Sheet]![& labelname &].Caption
Is not concatenating a string, as [Forms] and [Bal_Sheet] refer to objects.
Instead, you should use:
b = Forms("Bal_Sheet").Controls(labelname).Caption
So basically I'm trying to write the below code to the database and I have the primary key as an Int and it was autogen but when writing to the database it didnt allow me to do it kept telling me that I wasn't allowed to enter a null value (because the code is obviously not writing to the primary key field) so I used the line
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
But the problem is I have to change the value each time I want to test a new record i.e. 1,2,3,4 and so on. I was wondering is there a line of code I can put in to make it create a value by adding +1 each time so I don't need to go into the code and enter a new number each time. Below is the full code writing to the database so you can see a better view of it
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim recordsAffected As String
Dim cmdstring As String = "INSERT [Event Table](EventID, EventTypeID, EventName, VenueName, NumberOfGuests, Date, ClientAddress, WeddingName, BuildingAddress) Values(#EventID, #EventTypeID, #EventName, #VenueName, #NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress)"
Con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\YellowDoor.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
cmd.Parameters.Add("#EventName", SqlDbType.Text).Value = EventNametxt.Text
cmd.Parameters.Add("#VenueName", SqlDbType.Text).Value = VenueLoDD.SelectedValue
cmd.Parameters.Add("#NumberOfGuests", SqlDbType.Int).Value = CInt(NumOfGtxt.Text)
cmd.Parameters.Add("#Date", SqlDbType.Int).Value = CInt(DateTxt.Text)
cmd.Parameters.Add("#ClientAddress", SqlDbType.Text).Value = txtAddress.Text
cmd.Parameters.Add("#WeddingName", SqlDbType.Text).Value = txtWedding.Text
cmd.Parameters.Add("#BuildingAddress", SqlDbType.Text).Value = txtBAddress.Text
Con.Open()
recordsAffected = cmd.ExecuteNonQuery
Con.Close()
If your EventID is an IDENTITY column, you should never try to set a value for it.
Just ignore that field both as parameter or inside the INSERT command.
And you can retrieve the value assigned by the database engine to your field in this way
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim cmdstring As String = "INSERT [Event Table] " & _
"(EventTypeID, EventName, VenueName, NumberOfGuests, [Date], ClientAddress, " & _
"WeddingName, BuildingAddress) Values(#EventTypeID, #EventName, #VenueName, " & _
"#NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress); " & _
"SELECT SCOPE_IDENTITY()"
Using Con = New SqlConnection(".....")
Using cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
.....
Con.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
Dim newEventID = Convert.ToInt32(result)
....
End If
End Using
End Using
With this code you don't pass anything for the EventID field but you add a second command text to your query. This second command will return the last value generated for an IDENTITY column by the database for your connection. This double command (A.K.A. batch commands) is executed using ExecuteScalar because we are interested in the single value returned by the SELECT SCOPE_IDENTIY()
Notice also that DATE is a reserved word in T-SQL so it is possible to use it as name of a column only if you enclose it in square brackets
I'm trying to get my program to generate new identifications based on the highest ID-number already within the database.
Dim kobling As New Tilkobling
Dim hentOrdreNummer As String = "SELECT MAX(ordreID) FROM bestilling"
Dim svar As DataTable
bOrdreID = hentOrdreNummer + 1
kobling.sporring(user, password, hentOrdreNummer)
svar = kobling.hentData()
All this returns is, ofcause, the sql-command (with the +1 it crashes due to string/integer i assume). Is there a simple way to do this?
New Code:
Dim kobling As New Tilkobling
Dim hentOrdreNummer As String = "SELECT * FROM bestilling"
Dim svar As DataTable
kobling.sporring(user, password, hentOrdreNummer)
svar = kobling.hentData()
Dim temprad As DataRow
Dim nyID, modID As String
For Each temprad In svar.Rows
nyID = temprad("ordreID")
modID = nyID + 1
bOrdreID = modID
This works, tho, It starts with the lowest number, and I get a error message untill it reach a number thats not already taken.
Working Code:
Dim kobling As New Tilkobling
Dim hentOrdreNummer As String = "SELECT MAX(ordreID) AS ordreID FROM bestilling"
Dim svar As DataTable
kobling.sporring(user, password, hentOrdreNummer)
svar = kobling.hentData()
Dim temprad As DataRow
Dim nyID, modID As String
For Each temprad In svar.Rows
nyID = temprad("ordreID")
modID = nyID + 1
bOrdreID = modID
Try this:
SELECT IFNULL(MAX(ordreID),0)+1 FROM bestilling
It will return the new possible ID i.e., max(id)+1.
You need to establish a connection to a database and actually run your SQL against it.
You then create a variable to store your result in and + 1 to your result.
You can not simply declare a string of "SELECT . . . . " and then expect to add + 1 to it.