Inner Exception Error VB.Net when Inserting into database - vb.net

I am trying to inset data into a sql server database, I have only started using VB this week so I am very new to it.
Here are my table definitions:
[betfair_place_bsp](
[bf_runner_id] [int] NOT NULL,
[bf_event_id] [varchar](12) NOT NULL,
[name] [varchar](255) NOT NULL,
[win] [int] NOT NULL,
[bsp_place] [decimal](6, 2) NOT NULL,
[ppwap] [decimal](6, 2) NOT NULL,
[early_traded] [numeric](18, 0) NOT NULL,
[pre_traded] [numeric](18, 0) NOT NULL,
[meeting_date] [date] NOT NULL,
[scheduled_time] [datetime] NOT NULL,
[country] [varchar](50) NOT NULL]
I am readin the data and then splitting it up by column
line = reader.ReadLine
Dim colsArray() As String = Split(line, ",")
I change the format of some of the columns
Dim meetingDate As String = Split(colsArray(3), " ")(0)
Dim scheduledTime As String = colsArray(3) + ":00"
Dim winLose As Integer = colsArray(6)
Dim backPrice As Decimal = Math.Round(Convert.ToDecimal(colsArray(7)), 2)
Dim weightedPrice As Decimal = Math.Round(Convert.ToDecimal(colsArray(8)), 2)
Dim earlyTraded As Decimal = Math.Round(Convert.ToDecimal(colsArray(14)), 0)
Dim preTraded As Decimal = Math.Round(Convert.ToDecimal(colsArray(15)), 0)
Then create the insert string
cmd.CommandText = "insert into betfair_place_bsp values(" + colsArray(4) + "," + "1." + colsArray(0) + ",'" + colsArray(5) + "'," + winLose _
+ ",'" + backPrice + "'," + weightedPrice + "," + earlyTraded + "," + preTraded + "," + meetingDate + ",'" + scheduledTime + "' + 'UK')"
When I try and tune the above line I get the following error:
System.InvalidCastException: 'Conversion from string "insert into betfair_place_bsp va" to type 'Double' is not valid.'
FormatException: Input string was not in a correct format.
I don't have anything of type 'Double'

On the advice given above I have used parameters rather than concatenating a string.
Dim newDataInsert As New betfair_data() With {.bf_event_id = "1." & colsArray(0), .bf_runner_id = colsArray(4), .name = colsArray(5), .bsp_place = colsArray(7),
.ppwap = colsArray(8), .early_traded = colsArray(14), .pre_traded = colsArray(15), .meeting_date = meetingDate, .scheduled_time = scheduledTime, .country = "UK", .win = colsArray(6)
}
db.InsertRow(newDataInsert)

Related

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.' Grid view update

I am working on a grid view update but System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression error. Please someone help.
protected void ResultGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtFName2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtFName");
TextBox txtDate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtSM");
TextBox txtCaseType2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCaseType");
TextBox txtFileno2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtFileno");
TextBox txtCustName2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCustName");
TextBox txtAddress2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCustName");
TextBox txtConno2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtConno");
TextBox txtPlotarea2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotarea");
TextBox txtPlotRate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotRate");
TextBox txtconstarea2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstarea");
TextBox txtConstFloor2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtConstFloor");
TextBox txtconstrate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstrate");
TextBox txtPlotvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotvalue");
TextBox txtconstvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstvalue");
TextBox txttotalvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txttotalvalue");
TextBox txtRemarks2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtRemarks");
**TextBox txtDatee2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtDate2");**
string da = txtDatee2.Text.ToString();
DateTime dt =
DateTime.ParseExact(da, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
string dateshort = dt.ToShortDateString();
string ID = ResultGridView.DataKeys[e.RowIndex].Values[0].ToString();
cmd.Connection = conn;
cmd.CommandText = "UPDATE Final SET Finance ='" + txtFName2.Text + "' ,SM ='" + txtDate2.Text + "',Case_Type ='" + txtCaseType2.Text + "',File_no ='" + txtFileno2.Text + "',Cust_Name ='" + txtCustName2.Text + "' ,Address ='" + txtAddress2.Text + "',Con_no ='" + txtConno2.Text + "' ,Plot_area ='" + txtPlotarea2.Text + "' ,Plot_Rate ='" + txtPlotRate2.Text + "' ,const_area ='" + txtconstarea2.Text + "' ,Const_Floor ='" + txtConstFloor2.Text + "' ,const_rate ='" + txtconstrate2.Text + "' ,Plot_value ='" + txtPlotvalue2.Text + "' ,const_value ='" + txtConno2.Text + "' ,total_value ='" + txttotalvalue2.Text + "' ,Remarks ='" + txtRemarks2.Text + "'**,Date2 = '"+ dateshort +"'** WHERE ID=" + ID + "";
conn.Open();
cmd.ExecuteNonQuery();
ResultGridView.EditIndex = -1;
FillVendorGrid();
conn.Close();
}
At least, first text expressions for date values should be formatted as to the ISO sequence:
string dateshort = dt.ToString("yyyy'/'MM'/'dd");
second, in Access, these must be wrapped in octothorpes:
"', Date2 = #" + dateshort + "# WHERE ID="
This must be modified for other datetime fields as well.
Or, do your self a big favour and turn to call a parameterised query.

VB 2010 INSERT INTO syntax error

Hello Good Afternoon I have a program in VB.Net that will Input data
from textboxes into Access Database here is sample image
This is the code I am using and it gives me an error
m = TextBox1.Text
b = "'" + TextBox2.Text + "'"
x = "'" + TextBox3.Text + "'"
d = TextBox4.Text
n = "'" + TextBox5.Text + "'"
Dim s2 As String
s2 = "insert into users2 ( num , name1 , pass , add , phone ) " & " values ( " + m + " , " + n + " , " + b + " , " + x + " , " + d + " ) "
Dim cmd2 As New OleDbCommand(s2, con)
cmd2.ExecuteNonQuery()
Looking forward that someone will enlighten my problem since its im starting to program.
TYSM for future help
You need to encapsulate values you want to insert into ''
. "values('" + m + "', '" + ...
2 I don't understand & operator between two parts of query in the beginning

String Constant must End with double quote SQL report

Below is the query for a sql report that I am completing in SQL Server Business Studio and I keep getting an error regarding the double quotes on this line Dim SelectClause as System.String = ""
I tried a few things but I get the repeating error.
Any help would be appreciated.
Function getSelectClause(ByVal startDate as DateTime, ByVal endDate as DateTime) as String
Dim SelectClause as System.String = ""
SelectClause ="SELECT Define.meterName, SUM(Reading.volume) AS [Total Volume], MIN(Reading.time) AS [Month]
FROM [Reading] INNER JOIN Define ON Reading.meterId = Define.meterId
WHERE (Reading.[time] >= " & startDate & " AND Reading.[time]< " & endDate & ")
AND Define.meterName IN ('007080')
AND (Reading.dataQuality = '11' OR
Reading.dataQuality = '10') AND (Reading.auditVersion = '0')
GROUP BY Define.meterName"
return SelectClause
End Function
SSRS uses VB as its language for custom functions, which has a different syntax that SQL. VB does not support multi-line statements like SQL does. You need to end each line with " + _ and begin the continuation with ", and change how you append the date strings :
Function getSelectClause(ByVal startDate as DateTime, ByVal endDate as DateTime) as String
Dim SelectClause as System.String = ""
SelectClause ="SELECT Define.meterName, SUM(Reading.volume) AS [Total Volume], " + _
" MIN(Reading.time) AS [Month]" + _
" FROM [Reading] INNER JOIN Define ON Reading.meterId = Define.meterId" + _
" WHERE (Reading.[time] >= '" + startDate + "' AND Reading.[time]< '" + endDate+ "')" + _
" AND Define.meterName IN ('007080')" + _
" AND (Reading.dataQuality = '11' OR " + _
" Reading.dataQuality = '10') AND (Reading.auditVersion = '0') " + _
" GROUP BY Define.meterName"
return SelectClause

Inserting Identity values from dataset into table using table adapter VB.net

Is there any way to get the table adapter to insert the values already in the dataset I pass it when inserting new rows?
I am synchronising two databases and this would be useful.
Here is currently how I am trying to do it but it auto increments and creates new identity values.
Dim dAdapterConstraints As New SqlClient.SqlDataAdapter("SELECT * FROM " + Tablename, _oConn)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dAdapterConstraints)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
dAdapterConstraints.InsertCommand = builder.GetInsertCommand
Dim insertcommandstr As String = dAdapterConstraints.InsertCommand.CommandText.Substring(0, dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1) + " [" + Primarykey + "], " + dAdapterConstraints.InsertCommand.CommandText.Substring(dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1, dAdapterConstraints.InsertCommand.CommandText.Length - (dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1))
insertcommandstr = insertcommandstr.Replace("#p1", "#po1, #p1")
dAdapterConstraints.InsertCommand.Parameters.Add("#po1", getdbtype(dataset.Tables(0).Columns(Primarykey).DataType), dataset.Tables(0).Columns(Primarykey).MaxLength, Primarykey)
insertcommandstr = "SET IDENTITY_INSERT [" + Tablename + "] ON " + insertcommandstr + " SET IDENTITY_INSERT [" + Tablename + "] OFF"
dAdapterConstraints.InsertCommand.CommandText = insertcommandstr
dataset.EnforceConstraints = False
' opens connection
'fills dataset with results
Try
For Each row As DataRow In dataset.Tables(0).Rows
row.SetAdded()
Next
dAdapterConstraints.Update(dataset)
Catch ex As Exception
_oConn.Close()
MsgBox("Could not execute query on server database," + ex.ToString + ";Updating and inserting")
Return False
End Try

VB.net LINQ filter on multiple columns

Hi please can you advise me on the best way to achieve filtering on multiple columns in LINQ
Table:
CREATE TABLE [dbo].[user] (
[id] [int] IDENTITY(1,1) NOT NULL,
[firstName] [nvarchar](50) NULL,
[surname] [nvarchar](50) NULL,
[fullAddress] [nvarchar](1050) NULL
I would normally use SQL for this
Dim firstname as string = 'bob'
Dim surname as String = 'holdness'
Dim address as String = 'blockbuster street'
Dim Stmquery as string = 'Select * from users '
if not String.isnullorEmpty(firstname) or not String.isnullorEmpty(surname) or not String.isnullorEmpty(address) then
Stmquery = Stmquery & "where"
end if
if not String.isnullorEmpty(firstname) then
Stmquery = Stmquery & " firstname = " & firstname
end if
if not String.isnullorEmpty(surname) then
Stmquery = Stmquery & " surname = " & surname
end if
if not String.isnullorEmpty(address) then
Stmquery = Stmquery & " address = " & address
end if
So basically if the string is empty it will show all records for that column
Can someone show me how to do this in LINQ
Thanks Paul
I assume you already have LINQ to SQL DBContext prepared, with Users table mapped.
You can easily extend your query, because it's not going to be executed against database until you call ToList(), ToArray(), First(), Last(), etc.
Dim query = dbContext.Users;
If Not String.IsNullOrEmpty(firstname) Then
query = query.Where(Function(u) u.FirstName = firstname)
End If
If Not String.IsNullOrEmpty(surname) Then
query = query.Where(Function(u) u.Surname = surname)
End If
If Not String.IsNullOrEmpty(address) Then
query = query.Where(Function(u) u.Address = address)
End If
' query execution is here, after next line '
Dim results = query.ToList()