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
Related
I need to make query when two fields similar show additional city field. How to make hide and show field when duplicate values in fields?
for example, you have a Textbox (Textbox1) to search for the (Name)
and another Textbox (Textbox2) for the (Surname)
also you have a Database (MyDatabase)
Containing table named (MyTable), with fields (PersonName, PersonSurName, PersonCity)
Also, Datagridview (DataGridView1)
Finally, A button (Button1)
Under Button1.Click event, use this code:
Using cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MyDatabase.accdb")
cnn.Open()
Try
Dim sql As String = "SELECT * FROM MyTable WHERE PersonName = #myname and PersonSurName = #mysurname"
Using cmd As New OleDbCommand(sql, cnn)
cmd.Parameters.AddWithValue("#myname", TextBox1.Text)
cmd.Parameters.AddWithValue("#mysurname", TextBox2.Text)
Dim da As New OleDbDataAdapter(cmd)
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
If dt.Rows.Count <= 1 Then
DataGridView1.DataSource = dt
Dim column3 As DataGridViewColumn = DataGridView1.Columns(2)
DataGridView1.Columns(2).Visible = False
Else
DataGridView1.DataSource = dt
End If
End Using
Catch ex As Exception
MessageBox.Show("error : " + ex.Message)
End Try
cnn.Close()
End Using
and you should get what you want...
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();
Can anyone help me on this? What I wanted to happen is that if the value exist in Table 1 (employee), it will then check Table 2 (mobilelist) if it also exist there. Here's the code:
Private Sub TextBox_IDNumber_LostFocus(sender As Object, e As EventArgs) Handles TextBox_IDNumber.LostFocus
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;password=12345;database=my_db"
Dim READER As MySqlDataReader
Dim READER2 As MySqlDataReader
Dim _isFound As Boolean = False
Dim _isExist As Boolean = False
Try
Mysqlconn.Open()
Dim empmr As String
Dim empml As String
Dim fn1 As String
Dim fn2 As String
Dim ln1 As String
Dim ln2 As String
empmr = "Select * from my_db.employee where IDNumber ='" & TextBox_IDNumber.Text & "'"
empml = "Select * from my_db.mobilelist where IDNumber = '" & TextBox_IDNumber.Text & "' AND DateAssigned is not Null AND DateReturned is Null"
Command = New MySqlCommand(empmr, Mysqlconn)
READER = Command.ExecuteReader
While READER.Read()
_isFound = True
fn1 = READER.GetString("FirstName")
ln1 = READER.GetString("LastName")
End While
If _isFound Then
TextBox_FirstName.Text = fn1
TextBox_LastName.Text = ln1
ElseIf Not _isExist Then
MessageBox.Show("Record Not Found in Master Data")
TextBox_IDNumber.Clear()
TextBox_FirstName.Clear()
TextBox_LastName.Clear()
TextBox_IDNumber.Focus()
End If
Catch ex As MySqlException
MessageBox.Show("Error!")
Finally
Mysqlconn.Dispose()
End Try
End Sub
Assuming you have the appropriate Primary Key and Foreign Key relationship between the tables Employee and MobileList you use this query to find records on the MobileList table for an employee:
Dim myQuery as string
myQuery = "SELECT FirstName, LastName, MobileNumber
FROM Employee
JOIN MobileList
ON Employee.IDNumber=MobileList.IDNumber
WHERE Employee.IDNumber=#ID"
Note: You should rename the IDNumber column on the MobileList to avoid confusion.
You should also improve your access to the database with the Using statement and take advantage of Parameters to prevent SQL injection:
Using myConn As New SqlConnection("Your connection string")
myConn.Open()
Using myCmd As New SqlCommand(myQuery, myConn)
myCmd.Parameters.AddWithValue("#ID", "Your ID value")
Using myReader As SqlDataReader = myCmd.ExecuteReader()
If myReader.HasRows Then
'There are mobile numbers issued to that ID'
Do While myReader.Read()
'Iterate through all existing records'
Loop
Else
'There are no mobile numbers issued to that ID'
End If
End Using
End Using
End Using
Keep in mind that this gives you the mobile numbers for a particular employee, it doesn't tell you if a particular employee exists.
i hope you can help me. Fist of all, sorry if my English is annoying, i'm not a native speaker.
I'm getting this error and i can't see what i'm doing wrong. I have a program that fills a local MySQL DB with data from another program that uses an OLEB DB.
So it compares the tables and upload new data on demand. But i'm getting this error with only one table using the same Sub that i used with other tables.
Unknown column 'lpedidos.serie' in 'field list'
The problem is that 'lpedidos.serie' exists indeed. So here is the code of the sub, please don't laugh, i know that maybe is extremely inefficient, but i'm just a noob.
Public Sub notIndexedTables(table As DataTable, table2 As DataTable, tableNA As String)
Dim temptable As DataTable
temptable = table.Clone
Dim tablename As String = temptable.TableName
Dim myAdapter As MySql.Data.MySqlClient.MySqlDataAdapter
Dim SQL As String
Dim newconn As New MySql.Data.MySqlClient.MySqlConnection
newconn = mysqlConnection()
newconn.Open()
SQL = "TRUNCATE " & tableNA
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
Dim command As MySql.Data.MySqlClient.MySqlCommand
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.DeleteCommand = command
myAdapter.DeleteCommand.ExecuteNonQuery()
For Each row As DataRow In table.Rows()
Dim columnNumber As Int32 = row.ItemArray.Count
Dim i As Integer = 0
Dim s1 As String = "("
For Each columna In row.ItemArray
i = i + 1
If i = columnNumber Then
s1 = s1 + CStr(table2.Columns.Item(i - 1).ColumnName) & ")"
Else
s1 = s1 & CStr(table2.Columns.Item(i - 1).ColumnName) & ", "
End If
Next
Dim s2 As String = "("
i = 0
For i = 0 To (columnNumber - 2)
s2 = s2 & "'" & CStr(row.Item(i)) & "', "
Next
s2 = s2 & "'" & CStr(row.Item(columnNumber - 1)) & "')"
SQL = "INSERT INTO " & tableNA & " " & s1 & " VALUES " & s2
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
' myCommand = New MySql.Data.MySqlClient.MySqlCommandBuilder(myAdapter)
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.InsertCommand = command
myAdapter.InsertCommand.ExecuteNonQuery()
Next
newconn.Close()
newconn.Dispose()
End Sub
Basically it takes the MySQL table (tableNA), truncates it (this procedure is for tables with no index, there is other procedure for tables with unique index) and fills it with the data from the OLEB table (table) and takes the column names from the temporal copy of the MySQL table (table2) (maybe there is no need to use the table2 in this case... but anyway).
Here is the exception and the value that SQL string takes when the exception is thrown.
And here is a screenshot of the table structure in phpMyAdmin.
When you declare the New MySqlConnection you need to put the connection string in there and specify the database name. Can you show your connection string?
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
If that doesn't solve the problem, then try another column name and make sure it isn't a reserved keyword.