VB.NET Incrementing Indexes - vb.net

I am having trouble incrementing the indexes of my list item properties. Here is the code.
Dim i As Integer = 0
For x As Integer = 1 To list.Count / 19
database.ExecuteCommand("INSERT INTO Contacts VALUES ('" + _
list.Item(i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "', '" + _
list.Item(++i) + "')")
Next
The ++i does not increment at all in the parameters.
Thanks

you need to use your loop variable (x) and increase the index in that manner.
I'm doing this in C# but I'm sure you will understand.
string sql = "INSERT INTO Contact VALUES ('";
for(int i = 1; i < list.Count ; i++)
{
sql += list.Item(i) + "', '";
}
sql = sql.Remove(sql.Length -1);
sql += ")";
Database.ExecuteCommand(sql);

VB.Net does not have an increment operator.

Add this Function
Function GetIncrementValue(ByRef x as Integer) as Integer
x=x+1
Return x
End function
Your Code will be......
Dim i As Integer = 0
For x As Integer = 1 To list.Count / 19
database.ExecuteCommand("INSERT INTO Contacts VALUES ('" + _
list.Item(i) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "', '" + _
list.Item(GetIncrementValue(i)) + "')")
Next
Enjoy....

Related

How to convert from type Dbnull to type Date

If IsDBNull(dgv_datapasien.Rows(i).Cells(11).Value.ToString) Then
tglcetak = dgv_datapasien.Rows(i).Cells(11).Value.ToString
With dgv_datapasien.Rows(iRowIndex)
cmdData.CommandText = "Update tabelpasien set no_lab ='" + .Cells(1).Value.ToString + "', no_rm ='" + .Cells(2).Value.ToString + "'
, nama ='" + .Cells(3).Value.ToString + "',jeniskelamin ='" + .Cells(5).Value.ToString + "'
, status ='" + .Cells(6).Value.ToString + "', tglmasuk ='" & FormatTglUniversal(.Cells(8).Value) & "'
, ruangasal ='" + .Cells(7).Value.ToString + "' ,dokterpengirim='" + .Cells(9).Value.ToString + "'
,analis='" + .Cells(10).Value.ToString + "',umur ='" + .Cells(4).Value.ToString + "',analyzer='" + .Cells(0).Value.ToString + "'
where no_lab ='" + .Cells(1).Value.ToString + "'"
' ,tglcetak='" & FormatDateNull(.Cells(11).Value) & "'
End With
cmdData.ExecuteNonQuery()
End If
I need to update database from datagridview by clicking button Update.
One of the field is about datePrint.
But, sometimes, my dateprint is dbnull.
so I have problem to update database because datePrint is dbnull.
my code always show "Conversion from type 'DbNull' to 'Date' type is not valid"
fyi: I use postgresql
Anyone know how to solve this?
You should check for the datePrint cell during building the SQL query and set the respective column (in your case tglcetak) to NULL if the source value is null, otherwise set it to the date value.
Assuming your source grid cell(11) contains the datePrint value:
With dgv_datapasien.Rows(iRowIndex)
cmdData.CommandText = "Update tabelpasien set no_lab ='" + .Cells(1).Value.ToString +
"', no_rm ='" + .Cells(2).Value.ToString +
"', nama ='" + .Cells(3).Value.ToString +
"', jeniskelamin ='" + .Cells(5).Value.ToString +
"', status ='" + .Cells(6).Value.ToString +
"', tglmasuk ='" & FormatTglUniversal(.Cells(8).Value) &
"', ruangasal ='" + .Cells(7).Value.ToString +
"', dokterpengirim='" + .Cells(9).Value.ToString +
"', analis='" + .Cells(10).Value.ToString +
"', umur ='" + .Cells(4).Value.ToString +
"', analyzer='" + .Cells(0).Value.ToString + "'"
If IsDBNull(.Cells(11).Value) Then
cmdData.CommandText &= ",tglcetak=NULL"
Else
cmdData.CommandText &= ",tglcetak='" & FormatTglUniversal(.Cells(11).Value) & "'"
End If
cmdData.CommandText &= " where no_lab ='" + .Cells(1).Value.ToString + "'"
End With
cmdData.ExecuteNonQuery()
I don't know what your FormatDateNull function returns, so I don't use it above. And I assume your function FormatTglUniversal formats the date string to postgresql date format.
I would recommend you get used to using parameterized query for security and performance since your code here is inside a loop.
Make sure Date Field in database allows null
while passing the parameter to database use below format
input parameter of database = (dateprint == DBNull.value ? null : (DateTime?)convert.toDateTime(dateprint))

VC++ SQL INSERT INTO error

I'm using VC++ (Visual C++) in my system. I'm doing to add student's information in a Access Database which I used SQL Command (INSERT INTO).
this is my codes to add student's information in access database
OleDb::OleDbConnection^ con = gcnew OleDb::OleDbConnection();
OleDb::OleDbCommand^ command = gcnew OleDb::OleDbCommand();
con->ConnectionString::set(conStr);
con->Open();
String^ cmdTxt = "
insert into students(studno, fname, lname,
mname, gender, status, birthday, course, shift, section, homeadd,
provadd, contactnum, nameguard, addguard, contguard, sec1, sub1,
room1, unit1, guro1, sec2, sub2, room2, unit2, guro2, sec3, sub3,
room3, unit3, guro3, sec4, sub4, room4, unit4, guro4, sec5, sub5,
room5, unit5, guro5, sec6, sub6, room6, unit6, guro6, sec7, sub7,
room7, unit7, guro7, sec8, sub8, room8, unit8, guro8, sec9, sub9,
room9, unit9, guro9, sec10, sub10, room10, unit10, guro10)
values('" + studno + "', '" + fname + "', '" + lname + "', '" + mname + "',
'" + sex + "', '" + status + "', '" + birthday + "', '" + course + "',
'" + shift + "', '" + section + "', '" + homeAdd + "', '" + provAdd + "',
'" + contactnum + "', '" + nameGuardian + "', '" + addGuardian + "',
'" + numGuardian + "', '" + se1 + "', '" + sub1 + "', '" + room1 + "',
'" + unit1 + "', '" + guro1 + "', '" + se2 + "', '" + sub2 + "',
'" + room2 + "', '" + unit2 + "', '" + guro2 + "', '" + se3 + "',
'" + sub3 + "', '" + room3 + "', '" + unit3 + "', '" + guro3 + "',
'" + se4 + "', '" + sub4 + "','" + room4 + "', '" + unit4 + "',
'" + guro4 + "', '" + se5 + "', '" + sub5 + "', '" + room5 + "',
'" + unit5 + "', '" + guro5 + "', '" + se6 + "', '" + sub6 + "',
'" + room6 + "', '" + unit6 + "', '" + guro6 + "', '" + se7 + "',
'" + sub7 + "', '" + room7 + "', '" + unit7 + "', '" + guro7 + "',
'" + se8 + "', '" + sub8 + "', '" + room8 + "', '" + unit8 + "',
'" + guro8 + "', '" + se9 + "', '" + sub9 + "', '" + room9 + "',
'" + unit9 + "', '" + guro9 + "', '" + se10 + "', '" + sub10 + "',
'" + room1 + "', '" + unit10 + "', '" + guro10 + "')";
command->Connection::set(con);
command->CommandText::set(cmdTxt);
command->ExecuteNonQuery();
con->Close();
No errors found when i compiled and run it, the problems is when i add student's information shows an error message
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
i checked many times in INSERT INTO, so i changed it
command->CommandText::set("insert into students("
+ "studno,"
+ "fname,"
+ "lname,"
+ "mname,"
+ "gender,"
+ "status,"
+ "birthday,"
+ "course,"
+ "shift)"
+ "values("
+ "'" + studno + "', '"
+ fname + "', '"
+ lname + "', '"
+ mname + "', '"
+ sex + "', '"
+ status + "', '"
+ birthday + "', '"
+ course + "', '"
+ shift + "')");
This code is works 100%, so I add fields,
command->CommandText::set("insert into students("
+ "studno,"
+ "fname,"
+ "lname,"
+ "mname,"
+ "gender,"
+ "status,"
+ "birthday,"
+ "course,"
+ "shift,"
+ "section)"
+ "values("
+ "'" + studno + "', '"
+ fname + "', '"
+ lname + "', '"
+ mname + "', '"
+ sex + "', '"
+ status + "', '"
+ birthday + "', '"
+ course + "', '"
+ shift + "', '"
+ section + "')");
so it gives me an error. -_-
so how to solve this problem
SECTION is a reserved word. If you surround that name with square brackets, Access will understand it is a field name. So change "section)" to "[section])"

MS Access VBA Data Type Mismatch Error in SQL Query

I currently have the following MS Access SQL Query which is part of an Access VBA function. It has been built with help from a previous question, which you can look at to better understand how it works.
sqlJoinQuery = "SELECT tbl_grp_by.[Field1],tbl_grp_by.[Field2], " & _
"Switch( " & _
"Nz(tbl_grp_by.[maxfield3]) = 0, '0', " & _
"Nz(tbl_grp_by.[maxfield3]) = 1, '>1 million', " & _
"Nz(tbl_grp_by.[maxfield3]) = 2, '0001-0010' " & _
") as [Field3], " & _
"tbl_grp_by.[" + commonField + "], " & _
"[" + tableName + "].* " & _
"INTO [" + newTableName + "] FROM (" & _
"SELECT Max([" + tableNameTemp + "].[Field1]) as [Field1], " & _
"Max([" + tableNameTemp + "].[Field2]) as [Field2], " & _
"Max(Switch( " & _
"Nz([" + tableNameTemp + "].[Field3]) = '0' , 0, " & _
"Nz([" + tableNameTemp + "].[Field3]) = '>1 million' , 1, " & _
"Nz([" + tableNameTemp + "].[Field3]) = '0001-0010', 2 " & _
"))as [maxField3], " & _
"[" + tableNameTemp + "].[" + commonField + "] as [" + commonField + "] " & _
"FROM [" + tableNameTemp + "] " & _
"INNER JOIN [" + tableName + "] " & _
"ON [" + tableNameTemp + "].[" + commonField + "] = [" + tableName + "].[" + commonField + "] " & _
"GROUP BY [" + tableNameTemp + "].[" + commonField + "] " & _
") as tbl_grp_by " & _
"INNER JOIN [" + tableName + "] " & _
"ON [" + tableName + "].[" + commonField + "] = tbl_grp_by.[" + commonField + "]"
The above Access query results in this SQL String:
SELECT tbl_grp_by.[Field1],
tbl_grp_by.[Field2],
Switch(Nz(tbl_grp_by.[maxfield3]) = 0, '0', Nz(tbl_grp_by.[maxfield3]) = 1, '>1 million', Nz(tbl_grp_by.[maxfield3]) = 2, '0001-0010') AS [Field3],
tbl_grp_by.[Finding ID],
[Issue_Management_Findings].* INTO [region_Issue_Management_Findings]
FROM
(SELECT Max([temp2_temp_Issue_Management_Findings].[Field1]) AS [Field1],
Max([temp2_temp_Issue_Management_Findings].[Field2]) AS [Field2],
Max(Switch(Nz([temp2_temp_Issue_Management_Findings].[Field3]) = '0', 0, Nz([temp2_temp_Issue_Management_Findings].[Field3]) = '>1 million', 1, Nz([temp2_temp_Issue_Management_Findings].[Field3]) = '0001-0010', 2))AS [maxField3],
[temp2_temp_Issue_Management_Findings].[Finding ID] AS [Finding ID]
FROM [temp2_temp_Issue_Management_Findings]
INNER JOIN [Issue_Management_Findings] ON Nz([temp2_temp_Issue_Management_Findings].[Finding ID]) = Nz([Issue_Management_Findings].[Finding ID])
GROUP BY [temp2_temp_Issue_Management_Findings].[Finding ID]) AS tbl_grp_by
INNER JOIN [Issue_Management_Findings] ON Nz([Issue_Management_Findings].[Finding ID]) = Nz(tbl_grp_by.[Finding ID])
So [Field3] is encoded under max() in the inner query and that max is decoded in outer query.
However, when I run it I get the following error:
Run-time error '3464': Data type mismatch in criteria expression
If I copy my SQL query from debug output in the immediate window and paste it in a manual SQL query (after running my VBA code up to a breakpoint where the SQL query should be run), then I get the following error:
Data type mismatch in criteria expression
If I only run the subquery in my above SQL string for debugging purposes:
(SELECT Max([temp2_temp_Issue_Management_Findings].[Field1]) AS [Field1],
Max([temp2_temp_Issue_Management_Findings].[Field2]) AS [Field2],
Max(Switch(Nz([temp2_temp_Issue_Management_Findings].[Field3]) = '0', 0, Nz([temp2_temp_Issue_Management_Findings].[Field3]) = '>1 million', 1, Nz([temp2_temp_Issue_Management_Findings].[Field3]) = '0001-0010', 2))AS [maxField3],
[temp2_temp_Issue_Management_Findings].[Finding ID] AS [Finding ID]
FROM [temp2_temp_Issue_Management_Findings]
INNER JOIN [Issue_Management_Findings] ON Nz([temp2_temp_Issue_Management_Findings].[Finding ID]) = Nz([Issue_Management_Findings].[Finding ID])
GROUP BY [temp2_temp_Issue_Management_Findings].[Finding ID])
Then it runs without error
Note that Issue_Management_Findings is the name of an existing table in the database.
Does anybody know how I could fix these errors?
I think you have to add default return value on your Switch just in case it fails to match all the other criteria so it wont return Null which I believe cause the Data Type mismatch issue. You can just add ...,true,"thedefaultvalue") e.g.
SWITCH (field>100, "greater", field3=100 ,"equals", true, "default")
so in your query. I default it to 0;
sqlJoinQuery = "SELECT tbl_grp_by.[Field1],tbl_grp_by.[Field2], " & _
"Switch( " & _
"Nz(tbl_grp_by.[maxfield3]) = 0, '0', " & _
"Nz(tbl_grp_by.[maxfield3]) = 1, '>1 million', " & _
"Nz(tbl_grp_by.[maxfield3]) = 2, '0001-0010' " & _
", true,'0') as [Field3], " & _
"tbl_grp_by.[" + commonField + "], " & _
"[" + tableName + "].* " & _
"INTO [" + newTableName + "] FROM (" & _
"SELECT Max([" + tableNameTemp + "].[Field1]) as [Field1], " & _
"Max([" + tableNameTemp + "].[Field2]) as [Field2], " & _
"Max(Switch( " & _
"Nz([" + tableNameTemp + "].[Field3]) = '0' , 0, " & _
"Nz([" + tableNameTemp + "].[Field3]) = '>1 million' , 1, " & _
"Nz([" + tableNameTemp + "].[Field3]) = '0001-0010', 2 " & _
", true, 0))as [maxField3], " & _
"[" + tableNameTemp + "].[" + commonField + "] as [" + commonField + "] " & _
"FROM [" + tableNameTemp + "] " & _
"INNER JOIN [" + tableName + "] " & _
"ON [" + tableNameTemp + "].[" + commonField + "] = [" + tableName + "].[" + commonField + "] " & _
"GROUP BY [" + tableNameTemp + "].[" + commonField + "] " & _
") as tbl_grp_by " & _
"INNER JOIN [" + tableName + "] " & _
"ON [" + tableName + "].[" + commonField + "] = tbl_grp_by.[" + commonField + "]"

Error converting data type varchar to float. C# VS

I have the following SQL statement which is giving me this error.
THIS IS NOT MY CODE!
"Error converting data type varchar to float" But i can't find the error.
I thnk the error is coming from this code:
birthday = (monthComboBox.SelectedItem) + "-" + (dayComboBox.SelectedIndex + 1) + "-" + yearTextBox.Text;
Int32 getIDBack = 0;
string query = "insert into reservation(first_name, last_name, birth_day, gender, phone_number, email_address, number_guest, street_address, apt_suite,city, state, zip_code, room_type, room_floor, room_number, total_bill,payment_type, card_type, card_number,card_exp,card_cvc, arrival_time, leaving_time, check_in, break_fast, lunch, dinner, supply_status, cleaning, towel, s_surprise, food_bill) values('" + firstNameTextBox.Text +
"', '" + lastNameTextBox.Text + "', '" + birthday + "', '" + genderComboBox.SelectedItem + "', '" + phoneNumberTextBox.Text + "', '" + emailTextBox.Text +
"', '" + (qtGuestComboBox.SelectedIndex + 1) + "', '" + addLabel.Text + "', '" + aptTextBox.Text + "', '" + cityTextBox.Text +
"', , '" + zipComboBox.Text + "', '" + roomTypeComboBox.SelectedItem + "', '" + floorComboBox.SelectedItem +
"', '" + roomNComboBox.SelectedItem + "', '" + finalizedTotalAmount + "', '" + paymentType +
"', '" + CardType + "','" + paymentCardNumber + "','" + MM_YY_Of_Card + "','" + CVC_Of_Card + "', '" + dateTimePicker1.Text + "', '" + dateTimePicker2.Text + "','" + checkin +
"', '" + breakfast + "','" + lunch + "','" + dinner + "', '" + foodStatus + "', '" + Convert.ToInt32(cleaning) + "', '" + Convert.ToInt32(towel) + "', '" + Convert.ToInt32(surprise) + "','" + foodBill + "');";
query += "SELECT CAST(scope_identity() AS int)";
SqlConnection connection = new SqlConnection(Hotel_Manager.Properties.Settings.Default.frontend_reservationConnectionString);
SqlCommand query_table = new SqlCommand(query, connection);
try
{
connection.Open();
getIDBack = (Int32)query_table.ExecuteScalar();
string userID = Convert.ToString(getIDBack);
SendSMS(getIDBack);
MetroFramework.MetroMessageBox.Show(this, "Entry successfully inserted into database. " + "\n\n" +
"Provide this unique ID to the customer." + "\n\n" +
"USER UNIQUE ID: " + userID, "Report", MessageBoxButtons.OK, MessageBoxIcon.Question);
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
ComboBoxItemsFromDataBase();
LoadForDataGridView();
reset_frontend();
GetOccupiedRoom();
ReservedRoom();
getChecked();
}
This generally means that one (or more) of the values is a number, rather than a string. If any of the values in a + expression is numeric, then the + is interpreted as addition rather than string concatenation.
One method is to find the offending values (such as finalizedTotalAmount) and then wrap them in conversions: cast(finalizedTotalAmount as varchar(255)).
A better way is to use parameterized queries, where the values are passed in as typed parameters. This is also safer because it prevents SQL injection.

Characters found after end of SQL Statement Error

First off I started my code with:
Comm2 = "INSERT INTO [Results]" _
& "([ResultsID], [TestID], [Thickness], [SNR], [STD], [M1], [M2], [kVp], [mAs], [TargetFilter])" _
& " values('" & CInt(NewRID) & " ', '" & CInt(NewRID) & " ', '" & Thickness & "', '" & SNR & "', '" & STD & "','" & M1 & "', '" & M2 & "', '" & kVp & "', '" & mAs & "', '" & TargetFilter & "')"
Comm3 = "INSERT INTO [Test]" _
& "([TestID], [Date], [MachineID], [RadiographerID])" _
& " values('" & CInt(NewRID) & " ', '" & todaysdate & " ', '" & 1 & " ', '" & UserID & " ',)"
However this didn't work as the tables are related in the database so had to change them at the same time, so i am currently trying this:
Comm2 = "INSERT INTO [Results] ([ResultsID],[TestID],[Tickness],[SNR],[STD],[M1],[M2],[kVp],[mAs],[TargetFilter]) VALUES('" & CInt(NewRID) & " ', '" & CInt(NewRID) & " ', '" & Thickness & "', '" & SNR & "', '" & STD & "','" & M1 & "', '" & M2 & "', '" & kVp & "', '" & mAs & "', '" & TargetFilter & "');" _
& "INSERT INTO [Test] ([TestID], [Date[, [MachineID], [RadiographerID]) VALUES('" & CInt(NewRID) & " ', '" & CDate(todaysdate) & " ', '" & CInt(MachineID) & "', '" & CStr(UserID) & "')"
OleDbInsertCommand.Connection = conn
OleDbInsertCommand.CommandText = Comm2
adapter2.InsertCommand = OleDbInsertCommand
adapter2.InsertCommand.ExecuteNonQuery()
And I am getting this error:
https://gyazo.com/36aa32cbfb0f54bbe571f6a9384114e1
Comm2 = "INSERT INTO [Results] ([ResultsID], [TestID], [Thickness], [SNR], [STD], [M1], [M2], [kVp], [mAs],[TargetFilter]) VALUES('" & CInt(NewRID) & " ', '" & CInt(NewRID) & " ', '" & Thickness & "', '" & SNR & "', '" & STD & "','" & M1 & "', '" & M2 & "', '" & kVp & "', '" & mAs & "', '" & TargetFilter & "')"
comm3 = " INSERT INTO [Test] ([TestID], [Date], [MachineID], [RadiographerID]) VALUES('" & CInt(NewRID) & " ', '" & CDate(todaysdate) & " ', '" & CInt(MachineID) & "', '" & CInt(UserID) & "')"
OleDbInsertCommand.Connection = conn
OleDbInsertCommand.CommandText = comm3
adapter2.InsertCommand = OleDbInsertCommand
adapter2.InsertCommand.ExecuteNonQuery()
OleDbInsertCommand.CommandText = Comm2
adapter2.InsertCommand = OleDbInsertCommand
adapter2.InsertCommand.ExecuteNonQuery()
Comm2 = "INSERT INTO [Results] ([ResultsID], [TestID], [Thickness], [SNR], [STD], [M1], [M2], [kVp], [mAs],[TargetFilter]) VALUES('" & CInt(NewRID) & " ', '" & CInt(NewRID) & " ', '" & Thickness & "', '" & SNR & "', '" & STD & "','" & M1 & "', '" & M2 & "', '" & kVp & "', '" & mAs & "', '" & TargetFilter & "')"
comm3 = " INSERT INTO [Test] ([TestID], [Date], [MachineID], [RadiographerID]) VALUES('" & CInt(NewRID) & " ', '" & CDate(todaysdate) & " ', '" & CInt(MachineID) & "', '" & CInt(UserID) & "')"
OleDbInsertCommand.Connection = conn
OleDbInsertCommand.CommandText = comm3
adapter2.InsertCommand = OleDbInsertCommand
adapter2.InsertCommand.ExecuteNonQuery()
OleDbInsertCommand.CommandText = Comm2
adapter2.InsertCommand = OleDbInsertCommand
adapter2.InsertCommand.ExecuteNonQuery()