connection()
k = "select community,unit,year,name,roll,mbl from info"
cmd = New SqlCommand(k, con)
dr = cmd.ExecuteReader
While (dr.Read())
If dr.GetString(0) = ComboBox2.Text And dr.GetString(1) = ComboBox3.Text And dr.GetString(2) = TextBox1.Text Then
k = "insert into co values(#community,#unit,#year,#name,#roll,#mbl)"
cmd = New SqlCommand(k, con)
cmd.Parameters.AddWithValue("#community", dr.GetString(0))
cmd.Parameters.AddWithValue("#unit", dr.GetString(1))
cmd.Parameters.AddWithValue("#year", dr.GetString(2))
cmd.Parameters.AddWithValue("#name", dr.GetString(3))
cmd.Parameters.AddWithValue("#roll", dr.GetString(4))
cmd.Parameters.AddWithValue("#mbl", dr.GetDecimal(5))
MsgBox("added success")
End If
End While
dr.Close()
cmd.ExecuteNonQuery()
this is my code..it retrieves two rows from the "info" table but it stores only one row(last row) to "bld" table.
Apart from your issue, why do you select all rows from that table and then check which record matches all user-selections at all? Instead you should only select the relevant records.
Or - since you actually want to insert into another table - insert only the relevant records without needing to select the rows at all:
Dim year As Int32
If Not Int32.TryParse(TextBox1.Text.Trim(), year) Then
MessageBox.Show("Please insert a valid year")
Return
End If
Dim insertSql =
"INSERT INTO co(community, unit, year, name, roll, mbl) " & vbCrLf & _
" SELECT community, unit, year, name, roll, mbl FROM info " & vbCrLf & _
" WHERE community = #community AND unit = #unit AND year = #year"
Using con = New SqlConnection("ConenctionString")
Using cmd As New SqlCommand(insertSql, con)
cmd.Parameters.Add("#community", SqlDbType.VarChar).Value = ComboBox2.Text
cmd.Parameters.Add("#unit", SqlDbType.VarChar).Value = ComboBox3.Text
cmd.Parameters.Add("#year", SqlDbType.Int).Value = year
con.Open()
Dim numInserted As Int32 = cmd.ExecuteNonQuery()
End Using
End Using
Related
Im trying to make an IN and OUT, and Have done the whole program with it's database... Now the last is how do I make a time buffer inorder not to get a duplicate record with the same time.
this is the code that I have done to create the running code... Question is How do I make the buffer. I have search through the internet yet I couldn't find the suitable method
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
status.Text = "IN"
End While
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
If (dr("entry_record")) = "IN" Then
record = "OUT"
ElseIf (dr("entry_record")) = "OUT" Then
record = "IN"
ElseIf (dr("entry_record")) = String.Empty Then
record = "IN"
End If
status.Text = (record)
End While
dr.Close()
cn.Close()
ConnectToDB()
sql = "insert into monitoring (id_num, fname, lname, status, entry_record, floor_level, date) VALUES (#num, #name, #lname, #stat, #record, #lev,#date)"
cmd = New MySqlCommand(sql, cn)
With cmd
.Parameters.AddWithValue("#num", idnum)
.Parameters.AddWithValue("#name", TextBox2.Text)
.Parameters.AddWithValue("#lname", TextBox6.Text)
.Parameters.AddWithValue("#stat", TextBox5.Text)
.Parameters.AddWithValue("#lev", levellock.sharevalue)
.Parameters.AddWithValue("#record", status.Text)
.Parameters.AddWithValue("#date", Date.Now)
.ExecuteReader()
End With
MsgBox("Details has been saved!", vbInformation, "Saved")
cmd = Nothing
dr.Close()
cn.Close()
I don't know if this what you meant because your english is horrible.
How about in the Date.Now you also include second so it become like this
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
y = Year
M = Month
d = Date
H = Hour
m = Minute
s = Second
I'm doing a VB with Access database and I want to create a button. Which savebutton with checking where the data that try to insert is duplicated or not compare with my database.
This my code, and the problem is whatever I enter it just show the user already exists.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
If (ComboBox2.Text = "") And (ComboBox3.Text = "")
And (TextBox3.Text = "") And (ComboBox4.Text = "")
Then
MsgBox("Please fill-up all fields!")
Else
Dim theQuery As String = ("SELECT * FROM Table1
WHERE"" [Subject_Code]=#Subject_Code ,[Day]=#Day,
[Times]=#Times , [Lecture]=#Lecture and [Class_Room]=#Class_Room""")
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, MyConn)
cmd1.Parameters.AddWithValue("#Subject_Code", TextBox6.Text)
cmd1.Parameters.AddWithValue("#Day", ComboBox2.Text)
cmd1.Parameters.AddWithValue("#Times", ComboBox3.Text)
cmd1.Parameters.AddWithValue("#Lecture", TextBox3.Text)
cmd1.Parameters.AddWithValue("#Class_Room", ComboBox4.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'User already exists
MsgBox("User Already Exist!")
Else
Dim Update As String = "INSERT INTO [Table1]
([Subject_Code], [Subject],
[Day], [Times], [Level],[Semester], [Lecture],[Class], [Class_Room])
VALUES (?,?,?,?,?,?,?,?,?)"
Using cmd = New OleDbCommand(Update, MyConn)
cmd.Parameters.AddWithValue("#p1", TextBox6.Text)
cmd.Parameters.AddWithValue("#p2", TextBox1.Text)
cmd.Parameters.AddWithValue("#p3", ComboBox2.Text)
cmd.Parameters.AddWithValue("#p4", ComboBox3.Text)
cmd.Parameters.AddWithValue("#p5", ComboBox1.Text)
cmd.Parameters.AddWithValue("#p6", ComboBox6.Text)
cmd.Parameters.AddWithValue("#p7", TextBox3.Text)
cmd.Parameters.AddWithValue("#p8", ComboBox5.Text)
cmd.Parameters.AddWithValue("#p9", ComboBox4.Text)
MsgBox("New Data Is Saved")
cmd.ExecuteNonQuery()
End Using
End If
End Using
End If
First of all take a quick look at your theQuery variable, it may just have been malformed from where you have typed it into SO, but if not try:
Dim theQuery As String = "SELECT * FROM Table1 " &
"WHERE [Subject_Code] = #Subject_Code " &
"AND [Day] = #Day " &
"AND [Times] = #Times " &
"AND [Lecture] = #Lecture " &
"AND [Class_Room] = #Class_Room"
Your check for a pre existing user is based upon 5 fields, the insert for new data has 9 fields. Without knowing the business case I can't be sure if this is correct or if the missing 4 fields are actually important to the check and causing unexpected rows to be returned.
Personally my next steps would be:
Put a breakpoint on the AddWithValue statements and check the values
are what you expect
Run the query with the values in SSMS/Access or equivalent and check the rows that come back are what you expect
I am trying to compare a combobox value with data stored already in database, if data doesn't exist then user should be informed that he should select a record from the list or write down the name which already exist in database!
Below is the code I have written for it:
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Try
'Declare new data adapter and new datatable for publisher id & Auhtor id and ISBN
' to check record exist already or no
Dim pda As New SqlDataAdapter
Dim pdt As DataTable
Dim matchPub_name As String = cboPub_id.Text
pda = New SqlDataAdapter("SELECT pub_name FROM publisher WHERE pub_name =#pub_name", cn)
pdt = New DataTable
pda.Fill(pdt)
Dim ada As New SqlDataAdapter
Dim adt As DataTable
Dim matchAuthor_name As String = cboAuthor_id.Text
ada = New SqlDataAdapter("SELECT author_name FROM author WHERE author_name =" & matchAuthor_name, cn)
adt = New DataTable
ada.Fill(adt)
Dim matchISBN As String = txtisbn.Text.ToString
da = New SqlDataAdapter("SELECT isbn from book WHERE isbn =" & "'" & matchISBN & "'", cn)
dt = New DataTable
da.Fill(dt)
If pdt.Rows.Count = -1 Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboPub_id, _
"*Please Select or type available Publishers or register new in Publisher form")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
ElseIf adt.Rows.Count = -1 Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboAuthor_id, _
"*Please Select or type available Authors or register new in Author form")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
ElseIf dt.Rows.Count > 0 Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboAuthor_id, _
"*a record with provided ISBN already exist in Database. Insert Unique ISBN")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Else
'Insert into Book Table
cmd = New SqlCommand("Insert into book(isbn, book_name, price, rack_no, no_of_books, staff_id, " _
& " pub_id, sub_code, author_id) values(#isbn, #book_name, #price, #rack_no, " _
& " #no_of_books, #staff_id, #pub_id, #sub_code, #author_id)", cn)
With cmd.Parameters
.AddWithValue("#isbn", txtisbn.Text).ToString()
.AddWithValue("#book_name", txtbook_name.Text)
.AddWithValue("#price", txtprice.Text)
.AddWithValue("#rack_no", txtrack_no.Text)
.AddWithValue("#no_of_books", TxtNo_of_Books.Text)
.AddWithValue("#staff_id", Convert.ToInt32(cboStaff_id.SelectedValue.ToString()))
.AddWithValue("#pub_id", Convert.ToInt32(cboPub_id.SelectedValue.ToString()))
.AddWithValue("#sub_code", cboSub_Code.Text)
.AddWithValue("#author_id", cboAuthor_id.SelectedValue)
End With
cmd.ExecuteNonQuery()
'Insert into Published_by Table
cmd = New SqlCommand("Insert into published_by(isbn, pub_id, pub_date, vol_no) " _
& " values(#isbn, #pub_id, #pub_date, #vol_no)", cn)
cmd.Parameters.AddWithValue("#isbn", txtisbn.Text).ToString()
cmd.Parameters.AddWithValue("#pub_id", Convert.ToInt32(cboPub_id.SelectedValue.ToString()))
cmd.Parameters.AddWithValue("#pub_date", DateTimePicker1.Text)
cmd.Parameters.AddWithValue("#vol_no", txtvol_no.Text)
cmd.ExecuteNonQuery()
'Insert into Authored_by Table
cmd = New SqlCommand("Insert into authored_by(isbn, author_id, completion_date) " _
& " values(#isbn, #author_id, #completion_date)", cn)
cmd.Parameters.AddWithValue("#isbn", txtisbn.Text).ToString()
cmd.Parameters.AddWithValue("#author_id", cboAuthor_id.SelectedValue)
cmd.Parameters.AddWithValue("#completion_date", dtpCompletion_Date.Text)
cmd.ExecuteNonQuery()
'MessageBox.Show("Record Saved Successfully", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
lblAlert.Text = ""
lblInfo.Text = "Saved"
End If
Catch ex As Exception
MessageBox.Show("Not Completed Because OF The Following Error " & "%" & ex.Message & "%", "Error", _
' MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
but when I am entering data in cboAuthor_Name which is not available in DB it gives error Invalid column name ' '
how to handle this? any help?
There are a couple of problems in your code. The worst one is the string concatenation to build an sql query. Then there is a lesser one in using an SqlDataAdapter filling a DataTable only to discover if a record exists or not.
You could change your code to
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Dim matchPub_name As String = cboPub_name.Text
Dim matchAuthor_name As String = cboAuthor_id.Text
Dim matchISBN As String = txtisbn.Text.ToString
Using conn = new SqlConnection(....constring here ....)
Using cmd = new SqlCommand("SELECT pub_name FROM publisher WHERE pub_name = #name", conn)
conn.Open
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = matchPub_name
Dim publisherName = cmd.ExecuteScalar()
if publisherName is Nothing Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboPub_name, _
"*Please Select .....")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Return
End If
cmd.CommandText = "SELECT author_name FROM author WHERE author_name = #name"
cmd.Parameters("#name").Value = matchAuthor_name
Dim authorName = cmd.ExecuteScalar()
if authorName is Nothing Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboAuthor_name, _
"*Please Select .....")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Return
End If
cmd.CommandText = "SELECT isbn from book WHERE isbn = #name"
cmd.Parameters("#name").Value = matchISBN
Dim isbnCode = cmd.ExecuteScalar()
if isbnCode IsNot Nothing Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(txtISBN, _
"*ISBN Exists .....")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Return
End If
' Now insert into Book Table '
End Using
End Using
End Sub
Using parameters is the correct way to pass values to your database instead of building a text that is subject to parsing problems (your original code misses the single quote around the name) and Sql Injection attacks. Using directly a command with ExecuteScalar doesn't require to build a datatable. ExecuteScalar returns the first column of the first row, if any, otherwise the return is nothing.
Notice also that I don't use a global connection object but build one on the spot and destroy it through the Using block. There is a mechanism called Connection Pooling that allow objects like a Connection to be rebuilt very easily and quickly.
con.Open();
SqlCommand cmd = new SqlCommand("sp_Addbookdetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#class", ddlclass.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#Booktype", txtbktype.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(txtqty.Text));
cmd.Parameters.AddWithValue("#price", Convert.ToInt32(txtPrice.Text));
I am trying to develop a management system for dentists, this the system i am developing
THIS MY PROGRAM'S SCREENSHOT
when the dentist inputted a data on a textbox, it will be saved on the database and whenever the dentist insert a data again on that textbox, instead of replacing the older data with a newer data, it will store the data, making the cell store multiple data
and this is my code for adding data into the table
table name: teethhistory
database name: PatientManagementSystem
Private Sub txtURThirdMolar_KeyDown(sender As Object, e As KeyEventArgs) Handles txtURThirdMolar.KeyDown
If e.KeyCode = Keys.Enter Then
MySqlConn.Open()
query1 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
reader = cmd1.ExecuteReader
If reader.HasRows Then
Dim i As Integer
With cmd
.Connection = MySqlConn
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar ='" & txtURThirdMolar.Text & "' WHERE Patient_ID_Number = " & lblID.Text
reader.Close()
i = .ExecuteNonQuery
End With
If i > 0 Then
MsgBox("Updated!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Failed", MsgBoxStyle.Information, "Failed")
End If
Else
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO teethhistory (Patient_ID_Number, Fullname, Up_Right_3rd_Molar )" &
"VALUES ('{0}' ,'{1}' ,'{2}')",
lblID.Text,
lblFullname.Text,
txtURThirdMolar.Text)
reader.close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Saved!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Saving failed.", MsgBoxStyle.Critical, "Failed")
End If
MySqlConn.close()
End If
End Sub
if you want to Append the Existing text In field with new data from textbox,use Update command as
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar = concat('" & txtURThirdMolar.Text & "',Up_Right_3rd_Molar) WHERE Patient_ID_Number = " & lblID.Text
for inserting values seperated by commas, just insert a comma before the string ion concat function.
hope i undestood your problem well and this solves it.
For a listbox loading txt file and now I want to send the contents to sql database in which there are two tables m.in user, comm
http://obrazki.elektroda.pl/8069892000_1409841532.png
How to do to add all items were recorded in the table at the same time with id user?
ex. http://obrazki.elektroda.pl/5048367700_1409841766.png
The following method works only when I select one item.
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Try
con.ConnectionString = "Server = x; User ID = x; Password = x; Database = x;"
con.Open ()
cmd.Connection = con
cmd.CommandText = "insert into ycomm (user, comm) values ('" & ListView2.Items (0) .SubItems (0) .Text & "', '" & ListBox1.SelectedItem & "')"
cmd.ExecuteNonQuery ()
Catch ex As Exception
Finally
con.Close ()
End Try
Call showData ()
I found this but dees now work, where is problem?
Replace:
cmd.CommandText = "insert into ycomm (user, comm) values ('" _
& ListView2.Items(0).SubItems(0).Text & "', '" & ListBox1.SelectedItem & "')"
With
cmd.CommandText = "INSERT INTO ycomm (user, comm) VALUES(#user, #comm)"
cmd.Parameters.AddWithValue("#user", ListView2.Items(0).SubItems(0).Text)
cmd.Parameters.Add("#comm", SqlDbType.VarChar)
For i As Integer = 0 To lst.Items.Count
cmd.Parameters("#comm").Value = lst.Items(i).Text
cmd.ExecuteNonQuery()
Next