I've been trying to write to my database and it's nearly complete the only problem Im having is with the radio values as there are two question asked within the webform both with a response of Yes or No. I found an example of this on stackover flow which was
Dim rbval As Integer
If RadioButton1.Checked Then
rbval = 1
Else
rbval = 2
End If
cmd.Parameters.Add(New SqlParameter("#ethics", SqlDbType.Int))
cmd.Parameters("#ethics").Value = rbval
But it didn't work and kept providing me with an error message and highlighting the cmd.ExecuteNonQuery section of the code. I then tried to play with it and put in:
Dim rbval As Integer
If RadYes0.Checked Then
rbval = 1
Else
rbval = 2
End If
cmd.Parameters.Add("#TeaAndCoffee", SqlDbType.Text).Value = RadYes0.Text
And it did work when I selected "Yes" but when I selected "No" the Yes value kept storing in the database and I can see where I went wrong from the code because its always going to select yes from the one I tried to fix. I was wondering if anyone had any suggestions? below is the full code
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim recordsAffected As String
Dim cmdstring As String = "INSERT [Event Table](EventTypeID, EventName, VenueName, NumberOfGuests, Date, ClientAddress, WeddingName, BuildingAddress, Canapes, Starter, MainCourse, Dessert, TeaAndCoffee) Values(#EventTypeID, #EventName, #VenueName, #NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress, #Canapes, #Starter, #MainCourse, #Dessert, #TeaAndCoffee)"
Con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\YellowDoor.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, Con)
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
cmd.Parameters.Add("#Canapes", SqlDbType.Text).Value = txtCanapes.Text
cmd.Parameters.Add("#Starter", SqlDbType.Text).Value = txtStarter.Text
cmd.Parameters.Add("#MainCourse", SqlDbType.Text).Value = txtMainCourse.Text
cmd.Parameters.Add("#Dessert", SqlDbType.Text).Value = txtDessert.Text
Dim rbval As Integer
If RadYes0.Checked Then
rbval = 1
Else
rbval = 2
End If
cmd.Parameters.Add("#TeaAndCoffee", SqlDbType.Text).Value = RadYes0.Text
Con.Open()
recordsAffected = cmd.ExecuteNonQuery
Con.Close()
Response.Redirect("MenuForm.aspx")
End Sub
Look at your table column type in your SQL database. If it's a bit (the most logic way) it's as simple as a pie:
cmd.Parameters.Add("#Yourparam", SqlDbType.Bit).Value = IIf (Radyes0.Checked,1,0)
For Char type:
cmd.Parameters.Add("#Yourparam", SqlDbType.Char).Value = IIf (Radyes0.Checked,"Y","N")
For NVarchar type:
cmd.Parameters.Add("#Yourparam", SqlDbType.Nvarchar).Value = IIf (Radyes0.Checked,"Yes","No")
A simple look at your table design will tell you whichever sentence you need. Use always the same datatype of your database.
By the way: The reason because this example
Dim rbval As Integer
If RadYes0.Checked Then
rbval = 1
Else
rbval = 2
End If
cmd.Parameters.Add("#TeaAndCoffee", SqlDbType.Text).Value = RadYes0.Text
Always saved Yes to your database, is because radiobutton.text gives the text label of the radiobutton, I believe you had a radiobutton for yes and a radiobutton for no, right?
Related
that's my first time here, I'm going mad because of this problem I have:
I'm developing a windows form application with VB.NET using multiple types of connections(mysql,odbc and SQL server) everything works fine until I get into MySQL..
MySQL server is a physical windows 7 pc, I connect to it through IPSEC VPN TUNNEL.
I need to perform 2 MySQL connections every x seconds, if I get some type of result after the first connection then I'll open the second one, and so on every x seconds(that's all wrote in my timer.tick event handler).
The problem is that quite often some connections on MySQL server keep staying alive(ESTABLISHED) on MySQL server and I can't find out why... code looks fine, there are both open and close methods declared at the right time, I've also tried Dispose,ClearPool and ClearAllPools methods but I keep having those connections up until I close my program or it reaches connection limit.
Here's the code:
Class connection:
Public Sub connMySQL()
Dim connstring As String
Try
If stabilimento = "1PR" Then
If cesoia = "" Then
connstring = "server=192.168.123.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Else
connstring = "server=192.168.123.253;userid=xx;password=xx;database=xx;Connect Timeout=30"
End If
End If
If stabilimento = "2PR" Then
If cesoia = "" Then
connstring = "server=192.168.1.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Else
connstring = "server=192.168.123.253;userid=root;password=xx;database=xx;Connect Timeout=30"
End If
End If
conMySql = New MySqlConnection(connstring)
If conMySql.State = ConnectionState.Closed Then
conMySql.Open()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Class where the iteration is performed:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
connMySQL()
comm = New MySqlCommand("SELECT count_1,count_2,start_stop,data_ora,id FROM plc_contatori where plc_nome='" + plc_nome + "' and data_ora > '" + data_ieri.ToString("yyyy/MM/dd") + "' order by data_ora desc limit 1", conMySql)
dr = comm.ExecuteReader()
While (dr.Read())
count_1(0) = dr.GetValue(0)
start_stop(0) = dr.GetValue(2)
data_ora(0) = dr.GetValue(3)
If id <> dr.GetValue(4) And count_2(0) <> dr.GetValue(1) Then
id = dr.GetValue(4)
count_2(0) = dr.GetValue(1)
Else
Exit Sub
End If
End While
dr.Close()
dr.Dispose()
conMySql.Close()
conMySql.Dispose()
conMySql.ClearPool(conMySql)
conMySql.ClearAllPools()
If Not conMySql Is Nothing Then conMySql = Nothing
comm.Dispose()
If start_stop(0) = 1 Then
Exit Sub
End If
Dim dum_count_2 As Integer = count_2(0) - 1
connMySQL()
comm = New MySqlCommand("select count_1,count_2,start_stop,data_ora from plc_contatori where plc_nome='" + plc_nome + "' and data_ora > '" + data_ieri.ToString("yyyy/MM/dd") + "' AND count_2=" + dum_count_2.ToString + " ORDER BY data_ora desc limit 1", conMySql)
dr = comm.ExecuteReader()
While (dr.Read())
count_1(1) = dr.GetValue(0)
count_2(1) = dr.GetValue(1)
start_stop(1) = dr.GetValue(2)
data_ora(1) = dr.GetValue(3)
End While
dr.Close()
dr.Dispose()
conMySql.Close()
conMySql.Dispose()
conMySql.ClearPool(conMySql)
conMySql.ClearAllPools()
If Not conMySql Is Nothing Then conMySql = Nothing
comm.Dispose()
If count_1(0) = count_1(1) And start_stop(1) <> 1 And count_2(0) <> count_2(1) Then
'sub that reads some values from an odbc connection
CheckFermo()
End If
End Sub
NOTE that variables that I have not declared in this portion of code are declared in the public class of the form.
I'm wondering what could be wrong... maybe the 2nd connection is being established before the 1st one gets closed by the server?
I changed the connMySQL method to a function that returns the connection string. I have declared several variables so the code makes sense. I made several assumptions about datatypes. You may have to change this back to String and VarChar if these values are actually stored as strings. (I hope they are not)
You could use a single connection but all the assignments and comparisons would occur with an open connection.
Private stabilimento As String
Private cesoia As String
Public Function connMySQL() As String
Dim connstring As String
Select Case True
Case stabilimento = "1PR" And cesoia = ""
connstring = "server=192.168.123.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Case stabilimento = "2PR" And cesoia = ""
connstring = "server=192.168.1.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Case Else
connstring = "server=192.168.123.253;userid=root;password=xx;database=xx;Connect Timeout=30"
End Select
Return connstring
End Function
Private count_1(10) As Integer
Private count_2(10) As Integer
Private start_stop(10) As Integer
Private data_ora(10) As Date
Private id As Integer
Private plc_nome As String
Private data_ieri As Date
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Using dt As New DataTable
Using cn As New MySqlConnection(connMySQL),
comm = New MySqlCommand("SELECT count_1,count_2,start_stop,data_ora,id
FROM plc_contatori
where plc_nome= #plcNome and data_ora > #dataOra
order by data_ora desc
limit 1", cn)
comm.Parameters.Add("plcNome", MySqlDbType.VarChar).Value = plc_nome
comm.Parameters.Add("dataOra", MySqlDbType.Date).Value = data_ieri '.ToString("yyyy/MM/dd")
cn.Open()
Using dr = comm.ExecuteReader
dt.Load(dr)
End Using 'closes and disposes reader
End Using 'closes and dispose connection and command
count_1(0) = CInt(dt(0)(0))
start_stop(0) = CInt(dt(0)(2))
data_ora(0) = CDate(dt(0)(3))
If id <> CInt(dt(0)(4)) AndAlso count_2(0) <> CInt(dt(0)(1)) Then
id = CInt(dt(0)(4))
count_2(0) = CInt(dt(0)(1))
Else
Exit Sub
End If
End Using 'disposes DataTable
If start_stop(0) = 1 Then
Exit Sub
End If
Dim dum_count_2 As Integer = count_2(0) - 1
Using dt As New DataTable
Using cn As New MySqlConnection(connMySQL),
comm As New MySqlCommand("select count_1,count_2,start_stop,data_ora
from plc_contatori
where plc_nome= #plcNome
and data_ora > #dataOra
AND count_2= #count2
ORDER BY data_ora desc
limit 1", cn)
comm.Parameters.Add("#plcNome", MySqlDbType.VarChar).Value = plc_nome
comm.Parameters.Add("#dataOra", MySqlDbType.Date).Value = data_ieri '.ToString("yyyy/MM/dd")
comm.Parameters.Add("#count2", MySqlDbType.Int32).Value = dum_count_2 '.ToString
cn.Open()
Using dr = comm.ExecuteReader()
dt.Load(dr)
End Using
End Using
count_1(1) = CInt(dt(0)(0))
count_2(1) = CInt(dt(0)(1))
start_stop(1) = CInt(dt(0)(2))
data_ora(1) = CDate(dt(0)(3))
End Using
If count_1(0) = count_1(1) AndAlso start_stop(1) <> 1 AndAlso count_2(0) <> count_2(1) Then
'sub that reads some values from an odbc connection
CheckFermo()
End If
End Sub
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();
please, can anybody explain why this code is not working?
Connection to mysql is made via mysql odbc driver (latest).
Parameter in Select command is not recognized.
I also tried to replace #param1 in Select command:
Select product_id from product where model = ?
code still not working.
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = #param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "#param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
'this line displays "Select product_id from products where model = #param"
'instead of "Select product_id from products where model = "TESTVALUE"..
'WHY??
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub
Where it says:
".CommandText = "SELECT product_id FROM products WHERE model = #param"
Change it to:
".CommandText = "SELECT product_id FROM products WHERE model = '#param'"
(I've put ' ' around the #param, keep in mind this is different to the " " that is surrounding this)
I'm not 100% sure but I'll post this as an answer anyway because I think it's correct:
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = :param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With
Thanks for your help. This code is already working:
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model LIKE ?"
//it seems it is important to add paramater right after commandtext
.Parameters.Add("#param", OdbcType.VarChar).Value = "%" + "TESTVALUE" + "%"
.Connection = DBCONT
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
//it should display SELECT product_id FROM products WHERE model LIKE ?
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub
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
I have managed to write the value of the first row in label1, but I do not know why I cannot get the value of second row in label2. Here is how far I've managed to come
myCommand.CommandText = "SELECT allText FROM tbltest"
myDatareader = myCommand.ExecuteReader
Do While myDatareader.Read()
label1.Text = myDatareader(0).ToString()
label2.Text = myDatareader(1).ToString()
Loop
PS! i get this error "index was outside the bounds of the array". What is it that I'm doing wrong?
PSS! With help from Alex, I wrote these and it fixed the problem.
What it does is, it reads the values and writes them as labels inside a Panel.
solution
Public Sub getit()
Dim count As Integer = 0
myCommand.CommandText = "SELECT allText FROM tbltest"
myDatareader = myCommand.ExecuteReader
Do While myDatareader.Read
count += 1
show(myDatareader(0).ToString, count)
Loop
End Sub
Public Sub show(ByVal name As String, ByVal count As Integer)
Dim allTextlabel As New Label()
allTextlabel.Location = New Point(10, (45 * (count)) + 1)
allTextlabel.Size = New Size(100, 25)
allTextlabel.Name = "lbl_" & name.ToString
allTextlabel.Text = name.ToString
Panel1.Controls.Add(allTextlabel)
End Sub
Since you requested just one column myCommand.CommandText = "SELECT allText FROM tbltest" which is allText you haven't any myDatareader(1) just first one which index is 0 myDatareader(0)
UPDATE I am not very strong in VB but you can try:
Dim Phrase() as string
i=0
Do While myDatareader.Read()
i=i+1
Phrase(i) = myDatareader(0).ToString();
Loop
label1.Text = Phrase(1).ToString()
label2.Text = Phrase(2).ToString()
label3.Text = Phrase(3).ToString()
label4.Text = Phrase(4).ToString()
label5.Text = Phrase(5).ToString()