Combining two Columns - sql

I have an SQL table with 4 columns. The fourth column is FullName. I want this column to autofill itself from the results of 2nd and 3rd Column. ie.Firstname and Middlename.
I have tried this code
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', CONCATE(Textbox2.text, ',', Textbox3.Text))"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")

The section CONCATINATE will be like the following:
"CONCATE('" & Textbox2.text &"',',','" & Textbox3.Text & "'))"
But i wont tell you to use like this, since it may a worst suggestion. I prefer you to use parameters as well to avoid injection and specifying the types.
Example:
Dim query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (" & _
"#adm,#fName,#mName,CONCATE(#fNameC,',',#mNameC))"
Dim cmd As New SqlCommand(query, cn)
cmd.Parameters.Add("#adm", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#fName", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mName", SqlDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.Add("#fNameC", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mNameC", SqlDbType.VarChar).Value = TextBox3.Text
'Execute the query here

Before query first store two textbox value in one variable
cn.Open()
Dim query As String
Dim fullname As String
fullname = TextBox1.text + "" + TextBox2.text
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & fullname & '")"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")

You can concatenate with String.Concat, and I advice you to use the Parameter to avoid sql injections, like this :
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", TextBox2.Text))
cmd.Parameters.Add(New SqlParameter("#MiddleName", TextBox3.Text))
cmd.Parameters.Add(New SqlParameter("#FullName", String.Concat(TextBox2.Text, ",", TextBox3.Text)))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")

Save the Firstname and Middlename values into variables and concat() them together before sending to the query.
cn.Open()
Dim query As String
Dim firstname As String
Dim middlename As String
Dim fullname As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
firstname = TextBox2.Text
middlename = TextBox3.Text
fullname = String.Concat(firstname, ",", middlename)
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", firstname))
cmd.Parameters.Add(New SqlParameter("#MiddleName",middlename))
cmd.Parameters.Add(New SqlParameter("#FullName", fullname))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Note that the query builder has been reformatted to remove vulnerability to SQL injection.

Use following line instead of your.
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & Textbox2.Text & " " & Textbox3.Text & "')"

Related

Need to close program to see datagrid changes after making a search query and update the results

I execute the search query and after that i want to update the results but datagridview doesnt update, need to close and reopen to see the results.
Can anyone help? dont know if the problem is in the update button or the search
Update button
Call cn()
Dim teste As String
teste = "UPDATE CARROS SET processo = '" & processo & "', estado = '" & estado & "', tecnico = '" & tecnico & "', data = #" & data & "# , localizacao = '" & localizacao & "', [Pedido/PI] = '" & pedido & "'
WHERE Código = " & codigo
updatee = New OleDb.OleDbCommand(teste, connection)
updatee.ExecuteNonQuery()
MessageBox.Show("Actualizado com sucesso")
connection.Close()
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
SEARCH Button
Dim locali As String
Call cn()
'Se não tem valor Erro
If pesqtxt.Text = "" Then
MsgBox("Introduz um Valor")
Else
locali = pesqtxt.Text
'Codigo SQL
sql = "Select *
FROM CARROS
WHERE (processo LIKE '%" & locali & "%') OR
(estado LIKE '%" & locali & "%') OR
(data Like '%" & locali & "%') OR
(localizacao Like '%" & locali & "%') OR
(tecnico Like '%" & locali & "%')"
oledbAdapter = New OleDbDataAdapter(sql, connection)
oledbAdapter.Fill(ds)
CARROSDataGridView.DataSource = ds.Tables(0)
CARROSTableAdapter1.Update(STOCKDataSet1.CARROS)
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
connection.Close()
As far as the Search code goes, you cannot find out if a String is "Like" as Date.
Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. Keep you database objects local and open connections as late as possible anc close as soon as possible.
Private Sub UpdateDatabse()
Using cn As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("UPDATE CARROS SET processo = #processo, estado = #estado, tecnico = #tecnico, data = #data , localizacao = #localizacao, [Pedido/PI] = #pedido WHERE Código = #codigo", cn)
With cmd.Parameters
.Add("#processo", OleDbType.VarChar, 50).Value = processo
.Add("#estado", OleDbType.VarChar, 50).Value = estado
.Add("#tecnico", OleDbType.VarChar, 50).Value = tecnico
.Add("#data", OleDbType.Date).Value = CDate(Data)
.Add("#localizacao", OleDbType.VarChar, 50).Value = localizacao
.Add("#peido", OleDbType.VarChar).Value = pedido
.Add("#codigo", OleDbType.Integer).Value = codigo
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Actualizado com sucesso")
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS) 'No way for me to check this
End Sub
Private Sub Search(locali As String)
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("Select *
FROM CARROS
WHERE (processo LIKE #processo) OR
(estado LIKE #estado) OR
(localizacao Like #localizacao) OR
(tecnico Like #tecnico);", cn)
With cmd.Parameters
.Add("#processo", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#estado", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#localizacao", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#tecnico", OleDbType.VarChar).Value = "%" & locali & "%"
End With
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
If dt.Rows.Count > 0 Then
CARROSDataGridView.DataSource = Nothing
CARROSDataGridView.DataSource = dt
Else
MessageBox.Show("No matching records found")
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Se não tem valor Erro
If pesqtxt.Text = "" Then
MsgBox("Introduz um Valor")
Return
End If
Search(pesqtxt.Text)
End Sub
Try the Refresh option on the grid after you have loaded the updated data.
CARROSDataGridView.DataSource = ds.Tables(0)
CARROSTableAdapter1.Update(STOCKDataSet1.CARROS)
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
CARROSDataGridView.Refresh

How to close the sqldatareader within Using statement?

I'd like to use this code to verify if duplication occurs or not before saving the data to the database. How am I supposed to close the sqldatareader? (As what the error shows me)
con.ConnectionString = "Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True"
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()
The error are referring to is because you must complete the execution of the data reader before you try to execute another command on the same connection.
Additionally there are some issues with your code:
It is strongly recommended you use and then dispose of SqlConnections as you use them, do not try to reuse these globally in your application. The ado.net SQL Server client library will handle connection pooling for you by default.
You need to use parameters with your insert just like you did on your select.
Do not to use AddWithValue when adding your parameters, instead use the constructor and also specify the sql data type. If RollNo is a number (like integer) then you should pass the value as an integer to your parameter. I assumed it was a string stored in a varchar.
Wrap all types that implement IDisposable in Using statements to ensure resources are always released. (In case any one wants to nitpick, no it is not required for SqlCommand in this case.)
Dim recordExists As Boolean
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("SELECT RollNo FROM Profile WHERE RollNo=#RollNo AND Name=#Name", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
Using reader As SqlDataReader = cmd.ExecuteReader()
recordExists = reader.HasRows
End Using
End Using
End Using
If recordExists Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("INSERT INTO Profile (RollNo, Name) VALUES (#RollNo, #Name)", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
End Using
End Using
End If
if you are using using then not need to close. because it internally close all connection. The code would be like this
using(var con=new Sqlconnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")){
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()}

i want to filter my data with this from using visual studio 2015

I want to sort the data in the database with the date as the main condition with 2 date time picker 1 as the starting date and the other as the limit with this code by using between but I do not know the correct query form...my from looks like this the first DTP name is DTPDari and second DTPSampai
Call KONEKSI()
CMD = New OleDbCommand("SELECT * FROM Pembayaran where tanggal_pembayaran BEETWEEN '" & DTPDari.Value & "'AND tanggal_pembayaran = '" & DTPSampai.Value & "'", CONN)
DR = CMD.ExecuteReader
DR.Read()`
From the little what I understand from your question you can use any of the below
(syntax not tested)
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran BETWEEN '" & DTPDari.Value & "' AND '" & DTPSampai.Value & "')
or
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran > '" & DTPDari.Value & "') and (tanggal_pembayaran < '" & DTPSampai.Value & "')
Adding Function sample asper your request
Sub GetDetails()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString.ToString()
Dim connection As New SqlConnection(connectionString)
Dim queryString2 = "SELECT *
FROM dbo.Customers
WHERE (CreationDate BETWEEN #param1 AND #param2)"
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = queryString2
cmd.Connection = connection
cmd.Parameters.AddWithValue("#Param1", from_DateTimePicker.Value.Date)
cmd.Parameters.AddWithValue("#param2", to_DateTimePicker.Value.Date)
connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
'here fill on datatable Or anything you want
End While
connection.Close()
End Sub

how to use multiple combo boxes to filter data

can someone please help me with this problem i'm a beginner in programming.
there is two comboboxes which is S.Y.(school year) and Sem(semester) and i want to use these two combo boxes to have more specific data in the listview below.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT edp_number, LastName + ', ' + FirstName as name, course as course, Address as address, syear as syear, Sem as sem FROM tblStudent"
If Me.cboSearchBy.Text = "1st" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%'"
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
this code only uses the sem combobox which is cboSearchby so now all i need to know is how to make combobox S.Y to function too and if also to use that texbox to search for firstname and lastname.
you just have to add another condition in your If statement:
If Me.cboSearchBy.Text = "1st" and Me.cboSY.Text = "2014-2015" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
End If
then if you want to add the searching for lastname and firstname, just add another condition on the IF-Statement.
Take Note: In using Logical Operator, AND is true if all condition is true while OR is true if atleast one of the conditions is true.

select and update query first row in a column

this is my select query, i was able to retrieve in a textbox. but when i updating, it updates all of its record in first column and i know that the reason is the 'ExecuteScalar', so anyone knows what should i replace in this? because i only want to update first row in a column?
Dim fname As New SqlCommand
Dim lname As New SqlCommand
Dim CMD As New SqlCommand
con = New SqlConnection("server=;uid=admin;pwd=t;database=")
con.Open()
fname = New SqlCommand("select first_name from employee_info where employee_id='" & TextBox1.Text & "';", con)
lname = New SqlCommand("select last_name from employee_info where employee_id='" & TextBox1.Text & "';", con)
CMD.Connection = con
TextBox3.Text = fname.ExecuteScalar
fname.ExecuteNonQuery()
TextBox4.Text = lname.ExecuteScalar
lname.ExecuteNonQuery()
by the way this is my update query....
fname = New SqlCommand("UPDATE employee_info SET first_name= '" & TextBox3.Text & "';", con)
fname.Connection = con
fname.ExecuteNonQuery()
lname = New SqlCommand("UPDATE employee_info SET last_name= '" & TextBox4.Text & "';", con)
lname.Connection = con
lname.ExecuteNonQuery()
Because you didn't specify which row you want to update. For example;-
fname = New SqlCommand("UPDATE employee_info SET first_name= '" & TextBox3.Text & "' WHERE [columnName]= '[columnValue]'", con)
fname.Connection = con fname.ExecuteNonQuery()