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.
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.
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()
I'm learning SQL Server and VB.NET. My problem is how to select and make a condition to specific row in the table.
Like, that I have table with two columns name, age, and I want to select rows where name is "XY".
After that, make a condition with an (if) statement like: if age (in the table) larger than 20.
Do some thing or each one his name "xy" print his age in a messagebox.
You can try this in one query like this:
select * from yourtable where name = 'XY' and age > 20
Noor, Rahul was exactly correct in what was recommended. It sounds like you have little experience with how to get data from a SQL query into a useable form so you can test and manipulate or analyze data. For technology, look at ADO, and ADOX usage in VB.NET with SQL queries. My recommendation is for you to purchase one or more good books on VB.NET, so you can fully understand how to move forward.
Dim filename As String = "C:\myfile.mdb"
Dim tablename as String = "mytable"
Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data source =" & filename
Dim cn As New OleDbConnection(ConnString)
cn.Open()
Dim qry As String
Dim cmd As New OleDbCommand(qry, cn)
qry = "SELECT * FROM [" & tablename & "] WHERE name = "XY" and age > 20 ORDER by age "
cmd.CommandText = qry
cmd.Connection = cn
Dim drdata As OleDbDataReader = cmd.ExecuteReader
Dim Cnt As Integer = 0
Dim name(), age() as Object
Do While drdata.Read
Cnt += 1
Redim Preserve name(Cnt)
Redim Preserve age(Cnt)
name(Cnt) = drdata.Item("name")
age(Cnt) = drdata.Item("age")
Loop
drdata.Close()
For i As Integer = 1 to Cnt
If age(i) = 20 Then
' do anything you want here
End If
Next i
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 have the following code where table name is student and column name is sem_of_study from the type of INT
Dim userquery As String = "select sem_of_study from student where username='" + Session("user") + "'"
Dim usercom As New SqlCommand(userquery, conn)
Dim a = usercom.ExecuteReader
I was wondering if I could convert the SQL Command into integer so I can use it in IF statements!!
so that variable a would
if a=1 then
else if a=2 then
Besides the fact you should use parameterized queries (search SO -- plenty of examples), you need to do something like this reading in the DataReader rows:
Dim a as Integer
Dim myReader As SqlDataReader = usercom.ExecuteReader()
If myReader.HasRows Then
myReader.Read()
a = myReader.GetInt32(0)
End If
And for the parameters:
Dim userquery As String = "select sem_of_study from student where username=#username"
Dim usercom as SqlCommand = new SqlCommand()
usercom.Connection = conn
usercom.CommandType = CommandType.Text
usercom.CommendText = userquery
usercom.Parameters.AddWithValue("username", Session("user"))