My VB.NET loop code doesn't work. Any Ideas? - vb.net

I'm making a script to help me out filling in a MySQL table. It basically loops through every year group and set and makes a class for their subject. For Example : Year Group 8, Set 4, English would be 84En etc etc. I made it so it loops through an ArrayList and changes some variables but I can't seem to get it to work.
I don't really know what to try to be honest because I've checked over it and I don't know if I'm blind but I don't see any errors.
Dim subjects As New ArrayList
subjects.Add("English")
subjects.Add("Welsh")
subjects.Add("French")
subjects.Add("Maths")
subjects.Add("Science")
subjects.Add("History")
subjects.Add("Geography")
subjects.Add("Pe")
subjects.Add("Re")
subjects.Add("Tutorial")
subjects.Add("Music")
subjects.Add("Drama")
subjects.Add("Technology")
subjects.Add("It")
subjects.Add("Art")
Dim upsubjects As New ArrayList
upsubjects.Add("English")
upsubjects.Add("Welsh")
upsubjects.Add("Physics")
upsubjects.Add("Biology")
upsubjects.Add("Chemistry")
upsubjects.Add("French")
upsubjects.Add("Maths")
upsubjects.Add("Science")
upsubjects.Add("History")
upsubjects.Add("Music")
upsubjects.Add("Technology")
upsubjects.Add("It")
Dim year As Integer = 7
Dim setting As Integer = 8
Dim done As Boolean = False
Dim cmd As MySqlCommand
While done = False
For Each subject As String In subjects
If year = 9 And setting = 8 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
End If
If setting = 8 And Not year = 9 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
year = year + 1
Else
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = setting + 1
End If
Next
For Each subject As String In upsubjects
If year = 11 And setting = 8 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
done = True
End If
If setting = 8 And Not year = 11 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
year = year + 1
Else
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = setting + 1
End If
Next
End While
I'm not getting any error messages, the form just loads (when the code is supposed to execute) and does nothing. Refreshed my MySQL database and nothing still. Any ideas on how to fix this??

If you're concatenating numeric values setting and year into your query string, don't you need to convert them to strings before you do so, with something like CStr()?
Not getting an error suggests to me that the code isn't being executed, but as others said in the comments, you can soon add a 'Stop' to check that.
Also, have a read up on "Database normalisation", with regard to combining various values into a single column in the table, think about how you're going to retrieve that information and how much easier it will be if you keep it separate.

Related

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

get data after union max and min sql statement

Is there any way to combine these sql statements in one statement:
Dim s As String =
"SELECT byu,MAX(atttime) AS attime FROM att
WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "'
and attdate ='" + curdate + "' and atttime>='" + mxtime + "'
and atttime<='" + mxtime2 + "' "
Dim xmd As New SqlCommand(s, con)
Dim dr As SqlDataReader = xmd.ExecuteReader
If dr.Read Then
DataGridView1.Rows(i).Cells(7).Value = dr("attime")
DataGridView1.Rows(i).Cells(14).Value = dr("byu")
End If
dr.close
Dim s2 As String =
"SELECT byu, MIN(atttime) AS attime FROM att
WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "'
and attdate ='" + curdate + "' and atttime>='" + mintime + "'
and atttime<='" + mintime2 + "' "
Dim xmd2 As New SqlCommand(s2, con)
Dim dr2 As SqlDataReader = xmd2.ExecuteReader
If dr2.Read Then
DataGridView1.Rows(i).Cells(4).Value = dr2("attime")
DataGridView1.Rows(i).Cells(15).Value = dr2("byu")
End If
dr2.Close()
the table att has data as:
pno attdate atttime byu
2 2015/01/02 07:05:02 0
2 2015/01/02 07:07:02 1
2 2015/01/02 18:08:11 0
2 2015/01/02 19:15:02 1
i was trying since morning and didn't come up with something, the problem that when i union the 2 sql statement i couldn't get the "byu" of MAX(atttime) and also the "byu" of MIN(atttime) via SqlDataReader. I almost red all the questions in the site that related to this and nothing worked for me so far.the result of above code is:
2 2015/01/02 07:05:02 0
2 2015/01/02 19:15:02 1
please help, thanks.
You can join you queries like this and execute them as a batch statement
Dim s As String =
"SELECT byu as byu1,MAX(atttime) AS attime1 FROM att
WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "'
and attdate ='" + curdate + "' and atttime>='" + mxtime + "'
and atttime<='" + mxtime2 + "' group by byu ;" +
"SELECT byu as byu2,MIN(atttime) AS attime2 FROM att
WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "'
and attdate ='" + curdate + "' and atttime>='" + mintime + "'
and atttime<='" + mintime2 + "' group by byu ;"
This is the only idea i dont know how many columns you are getting from database you have to set your cells() value respective of column order which you are getting from database
Dim xmd As New SqlCommand(s, con)
Dim dr As SqlDataReader = xmd.ExecuteReader
If dr.Read Then
DataGridView1.Rows(i).Cells(7).Value = dr("attime1")
DataGridView1.Rows(i).Cells(14).Value = dr("byu1")
DataGridView1.Rows(i).Cells(4).Value = dr("attime2")
DataGridView1.Rows(i).Cells(15).Value = dr("byu2")
End If

Sql query added to title?

In c# Windows Forms:
I'm having trouble adding a sql query result as text to a ToolStripMenuItem.Text.
The ToolStripMenuItem title should be, the company + how many orders there are in the sql table for this company which should update every x secounds.
Every 5 seconds it adds the query result to the text. My problem is that is "adds" it.
After the first 5 seconds it looks OK "rexton 1" but 5 seconds after it shows "rexton 1 1" and so on...
Here is my code:
//Rexton ordre klar til bestilling
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE firma = #rexton and udlevering BETWEEN #date and #dateadd";
command.Parameters.AddWithValue("#bernafon", "Bernafon");
command.Parameters.AddWithValue("#gn_resound", "GN Resound");
command.Parameters.AddWithValue("#oticon", "Oticon");
command.Parameters.AddWithValue("#phonak", "Phonak");
command.Parameters.AddWithValue("#rexton", "Rexton");
command.Parameters.AddWithValue("#siemens", "Siemens");
command.Parameters.AddWithValue("#widex", "Widex");
con.Open();
command.ExecuteNonQuery();
string result = command.ExecuteScalar().ToString();
con.Close();
if (result != "0")
{
rextonToolStripMenuItem.Text = rextonToolStripMenuItem.Text + " " + result;
rextonToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}
it is because you are setting rextonToolStripMenuItem.Text to rextonToolStripMenuItem.Text + " " + result which is appending to previous text
either set text to blank and set it again or just say
rextonToolStripMenuItem.Text = "rexton " + result

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

string concatation in sql query

i am having confusion with this string concatenation
could some body please brief me how this string concatenation taking place?
The confusion i am having is that, how this +, "", ' are working in this
int i = Magic.Allper("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Anything between two " characters is taken as a String in Java so "','" produces ','. SQL requires Strings wrapped in '. So "'" + venueTxt.Text + "'" parses to 'variable value' when the query is made.
("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Assuming that
Label1= Hello
companyTxt = ABC
txtBranch = Engineering
dateTxt = 2010-12-01
reportingTxt = Fergusson
venueTxt = Batcave
eligibilityTxt = No
The above values are replaced in the SQL statement, making it look like
("insert into tbl_notice values ('" + Hello + "','" + ABC + "','" + Engineering + "','" + 2010-12-01 + "' ,'" + Fergusson + "','" + Batcave + "','" + No + "')");
The "+" operator joins the string values, resulting in
("insert into tbl_notice values ('Hello','ABC','Engineering','2010-12-01' ,'Fergusson','Batcave','No')")
I strongly recommend that you don't use string concatenation in SQL queries. They provoque SQL injections. This will cause security issues.
What is SQL Injection?
In response to your question, this concatenation simply takes every TextBox.Text property value and concatenate it into your insert statement.
I strongly recommend that you're using parameterized queries using ADO.NET lise the following example (assuming SQL Server):
using (var connection = new SqlConnection(connString))
using (var command = connection.CreateCommand()) {
string sql = "insert into tbl_notice values(#label1, #companyTxt, #txtBranch, #dataTxt, #reportingTxt, #venueTxt, #eligibilityTxt)";
command.CommandText = sql;
command.CommandType = CommandType.Text;
SqlParameter label1 = command.CreateParameter();
label1.ParameterName = "#label1";
label1.Direction = ParameterDirection.Input;
label1.Value = Label1.Text;
SqlParameter companyTxt = command.CreateParameter();
companyTxt.ParameterName = "#companyTxt";
companyTxt.Direction = ParameterDirection.Input;
companyTxt.Value = companyTxt.Text;
// And so forth for each of the parameters enumerated in your sql statement.
if (connection.State == ConnectionState.Close)
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
I would use the string.Format method for clarity
int i = Magic.Allper(string.Format("insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));
You might also want to create an extension method that will make sure the strings are safe to pass to SQL in this fashion
public static string ToSqlFormat(this string mask, params string[] args)
{
List<string> safe = args.ToList();
safe.ForEach(a => a.Replace("'", "''"));
return string.Format(mask, safe);
}
which will let you write
string insert = "insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
int i = Magic.Allper(insert.ToSqlFormat(
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));