INSERT data from another table to another table with input OLEDB visual studio - insert-into

I want to get the value of Table1(vID) to auto transfer in table VOTED(vID) while the query has an select and insert this is what i am trying but i cant get it fix pls help.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO VOTED(vID) " & _
" VALUES (" & _
"SELECT(vID) FROM Table1 " & _
" WHERE (" & position & ")"
cmd.ExecuteNonQuery()
cnn.Close()
MessageBox.Show("Inserted sucessfully")
refreshdata()
Catch ex As OleDbException When ex.ErrorCode = -2147467259
MsgBox("FAILED")
End Try
End Sub

So 'SELECT(vID) FROM Table1 WHERE (SELECT vID from Table1,1)'. is not a valid SQL Statement. That is why it says "Syntax error."
Perhaps send me a tsql DDL script for the table designs and what you are trying to accomplish.

Related

SQL Connection error 40 000webhost with Visual Basic

I am pretty sure I have all of my information right here, but I keep getting this error
http://puu.sh/qoZDQ/7294d6e682.png
The code I used: (Not mine)
I have the right username password and database name (I think)
'SET THE CONNECTION BETWEEN VISUAL BASIC AND MYSQL DATABASE
Dim con As SqlConnection = New SqlConnection("Data Source=mysql9.000webhost.com;" & "Initial Catalog=databasename;" & "User ID=username;" & "Password=password;")
'A SET OF COMMAND IN MYSQL
Dim cmd As New SqlCommand
'SET A CLASS THAT SERVES AS THE BRIDGE BETWEEN A DATASET AND DATABASE FOR SAVING AND RETRIEVING DATA.
Dim da As New SqlDataAdapter
'SET A CLASS THAT CONSISTS SPECIFIC TABLE IN THE DATABASE
Dim dt As New DataTable
Dim sqlQuery As String
Dim result As Integer
Private Sub register(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'HOLDS THE DATA TO BE EXECUTED
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'EXECUTE THE DATA
Result = cmd.ExecuteNonQuery
'CHECKING IF THE DATA HAS BEEN EXECUTED OR NOT
If result > 0 Then
MsgBox("User has been registered.")
Else
MsgBox("Failed to register the user.")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub login(ByVal sqlQuery As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'FILLING THE DATA IN A SPECIFIC TABLE OF THE DATABASE
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
'DECLARING AN INTEGER TO SET THE MAXROWS OF THE TABLE
Dim maxrow As Integer = dt.Rows.Count
'CHECKING IF THE DATA IS EXIST IN THE ROW OF THE TABLE
If maxrow > 0 Then
MsgBox("Welcome " & dt.Rows(0).Item(4))
Else
MsgBox("Account does not exist.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Private Sub btn_Register_Click(sender As Object, e As EventArgs) Handles btn_Register.Click
sqlQuery = "INSERT INTO `dbuser` ( `user_name`, `user_username`, `user_pass`, `user_type`, `user_steamid`)" & "VALUES ('" & txtname.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "','" & cbotype.Text & "','" & txtsteamid.Text & "')"
register(sqlQuery)
End Sub
Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click
sqlQuery = "SELECT * FROM `dbuser` WHERE user_username ='" & txtusername.Text & "' AND user_pass = '" & txtpassword.Text & "'"
login(sqlQuery)
End Sub
I used the database info from here http://puu.sh/qoZXo/a391cba854.jpg (Also not my info just an example so I dont post my info publicly)
I fixed my issue with the help of what Plutonix commented
MySql is not the same thing as Microsoft SqlServer – Plutonix
So I did some googling and found this: https://dev.mysql.com/downloads/connector/net/
This is the .Net framework for MySql (I think thats the right terms)
anyhow installing this then changing the top line of my code from
imports System.Data.SqlClient
To:
imports MySql.Data.MySqlClient
and changing the sql variables in the code to MySql variables by just adding My to the first bit, and it seems to work "better" I now have a new issue, but its with 000webhosts mysql database, not the code.

Display an error if row already exists in insert data into SQL Server database using vb 2010

I have written a program to connect to SQL Server and insert data.
When I insert data into database with same StrUserID in SQL Server, it inserted data a second time, without an error Like that image in sql..
I need to ensure that data is only inserted into the database once, and if a row with the same StrUserID already exists, I need to display a message telling him "such a user name already exists".
Like that photo...
This is my code to insert data into database..
Query = "insert into TB_User (StrUserID,password) Values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
My second problem: when user create/insert data into sql I need to make password row change to MD5 not a normal password like the first photo in the first row...
Imports System.Data.SqlClient
Public Class Form2
Public mysqlconn As SqlConnection
Public command As SqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
mysqlconn = New SqlConnection
mysqlconn.ConnectionString =
"Data Source=MY-PC\SQLEXPRESS; initial catalog=SRO_VT_ACCOUNT;user id=sa;password=123"
Dim reader As SqlDataReader
Try
mysqlconn.Open()
Dim Query As String
Query = "insert into TB_User (StrUserID,password) Values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
command = New SqlCommand(Query, mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("Done")
mysqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
1 Build a unique constraint and handle the appropriate exception:
ALTER TABLE TB_User ADD CONSTRAINT UQ_USER_ID UNIQUE (StrUserID)
https://msdn.microsoft.com/en-us/library/ms190024(v=sql.120).aspx
2 Try HASBYTES function:
insert ...
values (:UserID, HASHBYTES('MD5', pwd))
https://msdn.microsoft.com/ru-ru/library/ms174415(v=sql.120).aspx

How to save vb.net combobox content into mysql table?

I have an issue here .. i cant save combobox content into my table ... all other data are successfully saved but the combo box is saved either 1 or zero .. what seems to be wrong?
My tables are designed through navicat .. does this have anything to do with my choice of data type? knowing that I chose the data type to be Text
This is my code and it shows no run errors
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conStr As String = ("Data Source=localhost;user id=root;password=123456;database=sam;")
Try
Dim con As New MySqlConnection(conStr)
Dim cmd As MySqlCommand
For i = 0 To ComboBox4.Items.Count
con.Open()
Dim sqls As String = "INSERT INTO initial_nom(f_name,s_name,th_name,fo_name,app_no,adm_type) VALUES('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "', '" & TextBox4.Text & "'," & TextBox5.Text & ",'" & ComboBox4.SelectedIndex.ToString & "')"
cmd = New MySqlCommand(sqls, con)
cmd.ExecuteNonQuery()
Next
Catch ex As Exception
MsgBox("Error in saving to Database. Error is :" & ex.Message)
End Try
End Sub
SelectedIndex is integer which point to index of the selected item. Assuming that combobox's data source contains collection of string, try to use SelectedItem instead, type-cast it to string :
DirectCast(ComboBox4.SelectedItem, String)

Is .ExecuteNonQuery() required to add sql data to a DB in vb.net

I am running the following code (part of it) to connect to PHPmyadmin DB
Private Sub sreg_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SqlConnection.ConnectionString = ServerString
Try
If SqlConnection.State = ConnectionState.Closed Then
SqlConnection.Open()
MsgBox("Successfully connected to MySQL DB")
Else
SqlConnection.Close()
MsgBox("Connection is Closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatment As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatment
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
MsgBox("Succesfully Added!")
SqlConnection.Dispose()
End Sub
However the .ExecuteNonQuery() is giving me huge headaches in terms of errors and problems. It uploads the data but, it can only do it once (one upload) before, it returns an error.
When I remove the .ExecuteNonQuery() no data gets uploaded? So I guess it is necessary.
Here is the code im uploading (part of it)
sql = "INSERT INTO students(student_id, title, initial, surname,
street, city, pcode, country ) VALUES ('" & strStudent & "', '"
& vtital & "', '" & vinital & "', '" & vsurname & "', '" & vstreet
& "', '" & vcity & "', '" & vpcode & "', '" & vcountry & "' )"
SaveNames(sql)
Hope my question makes sense and that I can get the message across
There are some errors in your approach to save this data that could lead to your problem.
The first problem is that code doesn't use a parameterized query. This is a security concern (Sql Injection) but also a simple logical problem. If you concatenate strings to build a sql query you have a problem with strings that contains characters with a special meaning for the database sql engine. What if one of your strings contains a single quote? It will be seen as the end of the string with the remainder of your text as invalid sql.
The second problem is the lacking of open/close/dispose of the MySqlConnection also in case of exceptions. This is resolved by using the Using Statement.
So I would rewrite your method as
Public SaveNames(ByRef SQLStatment As String, List(Of MySqlParameter) parameters) As Integer
Using con = new MySqlConnection(... put here the connection string...)
Using cmd = New MySqlCommand(SQLStatment, con)
if parameters.Count > 0 Then
cmd.Parameters.AddRange(parameters.ToArray())
End If
return cmd.ExecuteNonQuery()
End Using
End Using
End Function
And call it with code like this
sql = "INSERT INTO students(student_id, title, initial, surname," & _
"street, city, pcode, country ) VALUES (#id,#title,#init,#sur," & _
"#street,#city,#pcode,#country)"
Dim ps = New List(Of MySqlParameters)()
Dim p = new MySqlParameter("#id", MySqlDbType.Int32).Value = Convert.ToInt32(strStudent)
ps.Add(p)
p = new MySqlParameter("#title", MySqlDbType.VarChar).Value = vtital
ps.Add(p)
.. and so on for the other parameters.
.. respecting the actual datatype on the database table
.....
SaveNames(sql, ps)
Try this ...
cmd = New MySqlCommand( sqlstatement, conn)
conn.open()
cmd.ExecuteNonQuery()
conn.Close()
And as I suggested you .. use parameterized

how can i open execuete a query in VB while there is reader opened?

is there any possible way to execute this without getting this error "There is already an open DataReader associated with this Connection which must be closed first." i already tried using "dr.close()" and i get another error that says "Invalid attempt to Read when reader is closed." can you help me out?
Heres my code:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Label2.Text = AllPicker1.Text
Label3.Text = AllPicker2.Text
If AllPicker1.Value >= AllPicker2.Value Then
MsgBox("End Date Must be Greater!")
Else
Dim SQLstatement As String = "SELECT * FROM tblStudInfo,tbl_studentLog WHERE tblStudInfo.StudID = tbl_studentLog.StudentNumber AND tbl_studentLog.LoginDate BETWEEN '" & AllPicker1.Text & "' AND '" & AllPicker2.Text & "'"
OpenData(SQLstatement)
End If
End Sub
Public Sub OpenData(ByRef SQLstatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatement
.CommandType = CommandType.Text
.Connection = SqlConnection
dr = .ExecuteReader()
End With
While dr.Read
Dim SQLstatementSave As String = "INSERT INTO tbl_report (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) VALUES ('" & dr("StudID") & "','" & dr("Name") & "','" & dr("Course") & "','" & dr("Dept") & "','" & dr("LoginTime") & "','" & dr("LoginDate") & "') "
dr.Close()
Save(SQLstatementSave)
End While
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
Public Sub Save(ByRef SQLstatementSave As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatementSave
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
End Class
It seems you are using only one SqlConnection. For most database systems you cannot reuse the connection while you are reading from it. You can either read all data into memory / DataTable and work on the rows after that or use a different SqlConnection for your Inserts.
When working with SqlConnections, Readers and Commands I find the Using Statement very helpful to visualize object usage and creation.
We can reduce this down to a single query:
INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
SELECT StudID, Name, Course, Dept, LoginTime, LoginDate
FROM tblStudInfo
INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber
WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate
Note the use of the full INNER JOIN syntax. The older TableA,TableB syntax for joins should be avoided. Also note the use of placeholders for your dates. This is important.
Now I need to draw attention to a couple functions I saw: OpenData(), and Save().
Those two functions are fundamentally broken, because they force you to build your queries in a way that leaves you vulnerable to sql injection hacking. Someday soon, someone will put a value like this into a textbox that is included with a query:
';DROP Table tbl_studentLog;--
Think carefully about what would happen now if someone entered that into your AllPicker1.Text. It would be hard to do that to a date picker, but I'll bet you have other plain text fields that would allow this. The first character (single quote) in my proposed input would close the string literal in the query. The second character (semi-colon) would end the individual statement, but sql server won't stop executing code. The next set of characters make up an additional statement that would drop your table. The final two characters comment out anything that follows, to avoid sql server rejecting or not committing the command because of syntax errors. Yes, Sql Server will run that additional statement, if that is what you put in a textbox.
So, your methods as written are broken, because the only accept completed sql strings as input. Any function that calls into the database MUST also include a mechanism for accepting query parameters. You ultimately want to be running code more like this:
Public Sub CreateReport(ByVal StartDate As DateTime, ByVal EndDate As DateTime)
Dim sql As String = _
"INSERT INTO tbl_report " & _
" (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) " & _
" SELECT StudID, Name, Course, Dept, LoginTime, LoginDate " & _
" FROM tblStudInfo " & _
" INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber " & _
" WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate"
'.Net is designed such in most cases that you really do want a new SqlConnection for each query
'I know it's counter-intuitive, but it is the right way to do this
Using cn As New SqlConnection("Connection string"), _
cmd As New SqlCommand(sql, cn)
'Putting your data into the query using parameters like this is safe from injection attacks
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
One thing to point out here is that at first glance I don't close the connection. However, the Using block will ensure that the connection is closed promptly... even if an exception is thrown. Your existing code will leave the connection hanging in the case of a exception.
Also note that this neatly side-steps the whole issue of needing to execute a separate query while your reader is opened... but if you ever do really need to do this (it's rare), the answer is simple: use a separate connection.
Instead of:
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID") & "','" & etc.
Try using .ToString on your DR() references.
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID").ToString & "','" & etc.