OleDB Criteria Mismatch - sql

This is my last working code. It saves data from a burst of string. Using , as a delimiter, I added them into an array. Even if it has null values, it saves nothing on the DB.
Dim query As String = "INSERT INTO tblGPSRoutes" & _
"(UTCTime,Status,Latitude,NSIndicator,Longitude,EWIndicator," & _
"SpeedOverGround,CourseOverGround,UTCDate,MagneticVariation,EWIndicatorB,Mode,Cheksum)" & _
" VALUES " & _
"(#utctime,#status," & _
"#lat,#nsindicator," & _
"#long,#ewindicator," & _
"#sog,#cog,#utcdate,#magnet," & _
"#ewindicatorb,#mode,#checksum)"
Using cmd As New OleDbCommand(query, con) 'myconnection - is your connection object'
With cmd.Parameters
.AddWithValue("#utctime", txt(1))
.AddWithValue("#status", txt(2))
.AddWithValue("#lat", txt(3))
.AddWithValue("#nsindicator", txt(4))
.AddWithValue("#long", txt(5))
.AddWithValue("#ewindicator", txt(6))
.AddWithValue("#sog", txt(7))
.AddWithValue("#cog", txt(8))
.AddWithValue("#utcdate", txt(9))
.AddWithValue("#magnet", txt(10))
.AddWithValue("#ewindicatorb", txt(11))
.AddWithValue("#mode", txt(12))
.AddWithValue("#checksum", txt(13))
End With
cmd.ExecuteNonQuery()
This is my edited code because I need to parse the latlon datas.. this is where the title appears.. can you see what's wrong?
Dim la As Double = Double.Parse(txt(3).Substring(0, 2)) + Double.Parse(txt(3).Substring(2)) / 60.0
Dim lo As Double = Double.Parse(txt(5).Substring(0, 3)) + Double.Parse(txt(5).Substring(3)) / 60.0
Dim query As String = "INSERT INTO tblGPSRoutes" & _
"(UTCTime,Status,Latitude,NSIndicator,Longitude,EWIndicator," & _
"SpeedOverGround,CourseOverGround,UTCDate)" & _
" VALUES " & _
"(#utctime,#status," & _
"#lat,#nsindicator," & _
"#long,#ewindicator," & _
"#sog,#cog,#utcdate)"
Using cmd As New OleDbCommand(query, con) 'myconnection - is your connection object'
With cmd.Parameters
.AddWithValue("#utctime", txt(1))
.AddWithValue("#status", txt(2))
If txt(3) IsNot Nothing Then
.AddWithValue("#lat", la)
Else
.AddWithValue("#lat", "No Data") 'is this possible?'
End If
.AddWithValue("#nsindicator", txt(4))
If txt(5) IsNot Nothing Then
.AddWithValue("#long", lo)
Else
.AddWithValue("#long", "No Data")
End If
.AddWithValue("#ewindicator", txt(6))
.AddWithValue("#sog", txt(7))
.AddWithValue("#cog", txt(8))
.AddWithValue("#utcdate", txt(9))
End With
cmd.ExecuteNonQuery() 'error here..
End Using
I was thinking that maybe because I removed the number of data's to be inserted on a pre-made access database throws it? As you can see, I cut off the number of fields in code2 because there had been some error on the strings sent to me, and they are not that important, so I removed the code where they will be inserted in the DB, though their fields are still there. That was my first assumption (but I think not really)
Anyway, I did not test it yesterday so I thought about it. My GPS module hardly get signals so I can't test thoroughly, (strings were from it, so if it does not work, so am I)

Related

VB.net Checking if database exists before connecting to it

I found the following query in order to find out if a database table was created already or not:
if db_id('thedbName') is not null
--code mine :)
print 'db exists'
else
print 'nope'
Now I am wanting to use that same query within my VB.net application. This is the code I currently have elsewhere that connects to the database (that I am wanting to see if its there before doing all this):
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Initial Catalog=thedbName;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Of course the issue with this is that I have to know the database name first in order to connect to the database.
I then seem to be able to connect to the master database using this:
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
But that query seems to throw an error on Dim blah As String = cmd.ExecuteNonQuery() of:
Additional information: Incorrect syntax near ')'.
So I'm not all sure what I am missing in order to correct the issue with the query?
Need to know how to have the query come back and say 'exists' or 'nope'
Change Print() to Print (remove the parentheses.)
Better, don't use Print at all, use select.
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"select 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"select 'nope'"
Dim blah As String = CType(cmd.ExecuteScalar(), string)
ExecuteNonQuery returns the number of affected rows for updates and inserts. But what you are executing is a query.
ExecuteScalar returns the first column of the first row selected. The query above only returns one row with one value, so that's what it will return.
or do it like this
select * from sys.databases where [name] = 'thedbName'
if it returns a row, then the database exists, if not then it doesn't.
To check if a table exists within a database, use this
select * from sys.objects where [name] = 'theTableName' and type_desc = 'USER_TABLE'

how to call checkbox value from sql to display on form vb.net

am doing this but not working only apply in first record its working in insert and update
i stored in sql as true or false
Sub db_load()
On Error Resume Next
Dim pringdata As String = "SELECT custcode_" & _
",custname_" & _
",custname2_" & _
",phone_" & _
",mobile_" & _
",custadd_" & _
",date_" & _
",cutomerzone_ " & _
",check_ " & _
" FROM custInfo "
Dim sqlconload As New SqlConnection(sqlcon)
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "custInfo")
For i As Integer = ds.Tables(0).Rows.Count = 0 To -1
If ds.Tables(0).Rows(i).Item("check_") = "true" Then
checkActive.Checked = True
Else
checkActive.Checked = False
End If
Next
sqlconload.Close()
I gather you are referring to a specific customer since you're only setting a single checkbox? You'll need to modify your query to match that.
Next, examine how you're storing the "check" column. In most cases, converting to Bool will resolve it but you may have to special case it based on available values.
Also, if the field you're looking at could be null, you'll have to account for that as well.
Here's a good pattern to follow that properly disposes of resources such as connections, commands, and readers.
Public Sub db_load()
Using cn = New SqlConnection(sqlcon)
cn.Open()
Using cmd = New SqlCommand("SELECT custcode,custname,custname2,phone,mobile,custadddate,customerzone,check FROM custInfo", cn)
Using dr = cmd.ExecuteReader()
If dr.Read Then
checkActive.Checked = CBool(dr("check"))
End If
End Using
End Using
End Using
End Sub

How to read an excel while in use by another user with Oledb?

I have an excel on a shared drive and my application is using an Oledb connection to read data from the excel into a DataGridView.
cn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;" + "data source=" + skuPath + ";Extended Properties=""Excel 12.0;HDR=YES;""")
q1 = "select * from [" + year + "$B4:AM300]"
da = New System.Data.OleDb.OleDbDataAdapter(q1, cn)
Try
cn.Open()
da.Fill(ds, "Table1")
Catch e As OleDb.OleDbException
Dim errorMsg As String
Dim i As Integer
errorMsg = ""
For i = 0 To e.Errors.Count - 1
errorMsg += "Index #" & i.ToString() & ControlChars.Cr _
& "Message: " & e.Errors(i).Message & ControlChars.Cr _
& "NativeError: " & e.Errors(i).NativeError & ControlChars.Cr _
& "Source: " & e.Errors(i).Source & ControlChars.Cr _
& "SQLState: " & e.Errors(i).SQLState & ControlChars.Cr
Next i
End Try
cn.Close()
dt = ds.Tables(0)
When the excel file is already open by another user you get this notification in excel:
And in those situations my code returns this error on the last line:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: Cannot find table 0.
So i understand is that because the file is in use then the entire connection returns nothing and data table is therefore empty.
I found a few way of determining if a file is in use or not but nothing regarding how to read from a file in use.
Is it possible? and if so how?
Please remember i only need to read the file and if its possible to always open it as a readonly that would awesome!
You can't. You have to close the open file before read it even if you use the ODBC(read only).
Ref: http://forums.asp.net/t/1083489.aspx?open+a+Microsoft+Jet+OLEDB+4+0+connection+to+excel+file+read+only

Indexed Property error

While debugging my code I found an inner exception which reads as:
In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.
In sql the script runs smoothly returning all the rows, but in vb it's not returning or finding any rows. I have checked that the primary key is in the table and defined. How can I fix this? I had a proir query which returned rows, but as soon as I added this new query the inner exception came.... I didn't change anything except the querystring.
This is what I've done:
Public Sub BindDeliveredItems()
Proir if statemets....
Else
queryString = "select distinct LS.[Route], LS.[SubRoute], LS.[Truck], Convert(VARCHAR(10), LS.[Date], 121) AS Date, LS.[DriverAssistantContract]" & _
",((del.CT*100 )/ todel.TCT) as Score" & _
"from [Warehouse].[dbo].[LoadSheet] LS" & _
"left join (select [Truck],[Date],[Status], count([Status]) CT from [Warehouse].[dbo].[LoadSheet]" & _
"WHERE status='Delivered'" & _
"group by [Truck],[Date],[Status]) Del" & _
"on LS.truck=Del.truck and LS.[Date]=del.[Date]" & _
"left join (select [Truck],[Date], count([Truck]) TCT from [Warehouse].[dbo].[LoadSheet]" & _
"group by [Truck],[Date]) todel" & _
"on LS.truck=toDel.truck and LS.[Date]=todel.[Date]" & _
"WHERE ls.[Date] = '2013-07-03'" & _
"AND ls.[Truck] = 'BX 39 LK GP'"
End If
Dim ds As DataSet = GetData(queryString)
If (ds.Tables.Count > 0) Then
gvDeliveredItems.DataSource = ds
gvDeliveredItems.PageSize = (10)
gvDeliveredItems.AllowPaging = True
gvDeliveredItems.DataBind()
End If
End Sub
Function GetData(ByVal queryString As String) As DataSet
Dim ds As New DataSet()
Try
Dim adapter As New SqlDataAdapter(queryString, SQLCon)
adapter.Fill(ds)
Catch ex As Exception
MessageBox(ex.Message)
End Try
Return ds
End Function
EDIT:
The first time the I can see the exception is on this line
Dim ds As DataSet = GetData(queryString)
And on this line the exception shows as well:
If (ds.Tables.Count > 0) Then
My previous sql string work perfect without changing anything. The only thing I changed was the querystring when it started to give me this exception
I'd suggest adding more whitespace into your query, e.g.:
queryString = "select distinct LS.[Route], LS.[SubRoute], LS.[Truck], Convert(VARCHAR(10), LS.[Date], 121) AS Date, LS.[DriverAssistantContract]" & vbCrLf & _
",((del.CT*100 )/ todel.TCT) as Score" & vbCrLf & _
"from [Warehouse].[dbo].[LoadSheet] LS" & vbCrLf & _
vbCrLf is a VB-ism. If you prefer, you could use Environment.NewLine
At the moment, there are no new lines or spaces inside the string from this string concatenation, so for example, those second and third lines join together as:
,((del.CT*100 )/ todel.TCT) as Scorefrom [Warehouse].[dbo].[LoadSheet] LS
Which isn't what you wanted, presumably.

Unable to fill dataset with oracledataadpter

i am facing very strange problem , I am using the following piece of code but ds is not filled some times there is data in the ds but not always, I have change the connection pool and also restart the iis but no luck at all , I am not able to find where the problem is please help me out.
I am running the same query in the TOAD and its giving result , I have also commit the transaction for if any thing in inconsistent.
Dim command As New OracleCommand
Dim ds As New DataSet
Try
Using connection As New OracleConnection
(ConfigurationManager.ConnectionStrings("CA").ConnectionString.ToString())
connection.Open()
command.Connection = connection
command.CommandText = "SELECT w.portfolio, w.appl_group,
tm.trng_title, p.tt_program_title," & _
" p.created_date,
p.tt_target_completion_date, p.tt_prog_status," & _
" w.emp_id, w.first_name || ' ' ||
w.last_name, ('Y') training_done_flag," & _
" t.actual_completion_date,
p.created_by, w.people_manager, " & _
" w.project_manager, w.flag" &
_
" FROM tt_training_done_records t," & _
" wsr_employee w, " & _
" tt_training_master tm, " & _
" tt_newprogram p" & _
" WHERE(w.emp_id = t.employee_id)" & _
" AND t.training_info_id = tm.trng_id"
& _
" AND p.tt_program_id(+) =
t.program_id" & _
" AND tm.trng_id IN ( 'TT_009' ) " & _
" AND t.actual_completion_date BETWEEN
TO_DATE('11-Mar-2009') AND TO_DATE('11-Mar-2013') " & _
" "
Dim adpt As New OracleDataAdapter(command)
adpt.AcceptChangesDuringFill = False
adpt.Fill(ds)
connection.Close()
End Using
Don't rely on the default behavior of casting a string into a date. Either use a date literal or provide the format string argument. This introduces a dependency on NLS environment settings your .NET code should not depend upon.
Instead of TO_DATE('11-Mar-2013')
Try date '2013-03-11' or TO_DATE('11-Mar-2013'), 'DD-Mon-YYYY')