Why is Data Not Saved to the Database in my Guestbook Application? - sql

I am creating an application that requires a guestbook.. The data from the database appears on the website however any data I enter from the website doesn't automatically get put into the database.
Here is the code I have..
Protected Sub ButSign_Click(sender As Object, e As EventArgs) Handles ButSign.Click
Dim strDSN As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "
Data source=C:\USERS\SHAUNA WATSON\DESKTOP\PROJECT COPIES\FINAL\APP_DATA\FACTORY.MDF"
Dim strSQL As String = (((("INSERT INTO Guestbook " & "( Name,Address,Email,Comments)" & "VALUES ('")
+ TxtName.Text.ToString() & " ',' ") + TxtAddress.Text.ToString() & " ', '") + TxtEmail.Text.ToString() & " ',' ") + TxtComments.Text.ToString() & " ')"
' set Access connection and select strings
' Create oleDbDataAdapter
Dim myConn As New OleDbConnection(strDSN)
'Create ole Db Command And call ExecuteNonQuery to execute
' a SQL statement
Dim myCmd As New OleDbCommand(strSQL, myConn)
Try
myConn.Open()
myCmd.ExecuteNonQuery()
Catch exp As Exception
Console.WriteLine("Error: {0}", exp.Message)
End Try
myConn.Close()
' open Thans.aspx page after adding entries to the guest book
Response.Redirect("GuestbookThanks.aspx")
End Sub
I'm just wondering if anyone can spot something I may have missed!

You could try changing your code to this:
myConn.Open()
Dim myCmd As New OleDbCommand
With myCmd
.Connection = myConn
.CommandType = CommandType.Text
.CommandText = "INSERT INTO Guestbook (Name,Address,Email,Comments) VALUES (#Name,#Address,#Email,#Comments)"
.Parameters.Add("#Name", OleDbType.VarChar).Value = TxtName.Text
.Parameters.Add("#Address", OleDbType.VarChar).Value = TxtAddress.Text
.Parameters.Add("#Email", OleDbType.VarChar).Value = TxtEmail.Text
.Parameters.Add("#Comments", OleDbType.VarChar).Value = TxtComments.Text
End With
myCmd.ExecuteNonQuery()
myConn.Close()
Don't put this in a Try Block. If you get an error, just post it, and we'll see what the error is.

Related

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

SQL Update not updating records in access

Trying to update the values of Comment and ProgressValue inside a table in access. The message box at the end pops up but none of the values are changed.
Sub UpdateWeeklyReport()
Dim con As OleDbConnection
Dim com As OleDbCommand
con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\ProjectDatabase.mdb")
com = New OleDbCommand("Update WeeklyReport Set Comment = #Comment, ProgressValue = #ProgressValue Where [EntryDate]='" & CBDate.SelectedValue.ToString & "' AND [AdminNo]=" & CBAdmin.SelectedValue & " AND [ClassCode]='" & CBClass.SelectedItem.ToString & "'", con)
con.Open()
com.Parameters.Add("#Comment", OleDbType.LongVarChar).Value = txtComment.Text
com.Parameters.Add("#ProgressValue", OleDbType.Integer).Value = CBProgress.Text
com.ExecuteNonQuery()
con.Close()
MessageBox.Show("Report Changed")
intialconnection()
End Sub
End Class

Search between two dates in access database using sql

This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
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
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data

Retrieving/adding data from/to a stored procedure

Alright so I have this webpage that I have to create and it has 3 pages and a master page. Now basically all of it is working, except the fact that I can't seem to get data coming into the webpage when requested via a retrieve button, nor will it update or add data to the SQL table. Now in my queries page when I put Select * From Customer it brings back the data in the table so that part works. From what I have to work with in the pdf's provided, they want me to use
TextBox1.Text = table.Rows(0).Field<string>("TextBox1")
TextBox1.DataBind()
To retrieve the data from the sql, now it comes up with an error saying Overload resolution failed because no accessible 'Field' accepts this number of arguments.
So here is my Customer page
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data.DataRowCollection
Public Class Customer
Inherits System.Web.UI.Page
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Shadows adapter As SqlDataAdapter = New SqlDataAdapter()
// Tells me to use Shadows because variable adapter conflicts with property 'adapter'
Dim table As DataTable = New DataTable()
Dim command As SqlCommand = New SqlCommand()
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
conn = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Dim command As SqlCommand = New SqlCommand()
command.Connection = conn
command.CommandType = CommandType.Text
command.CommandText = "INSERT INTO Acme_Customer VALUES(" & txtCustID.Text & ",'" & txtFirstname.Text & "', '" & txtSurname.Text & "', " & txtGender.Text & ", " + txtAge.Text & ", " & txtAddress1.Text & ", " & txtAddress2.Text & ", " & txtCity.Text & ", " + txtPhone.Text & ", " + txtMobile.Text & ", " & txtEmail.Text & ")"
command.Connection.Open()
adapter.InsertCommand = command
adapter.InsertCommand.ExecuteNonQuery()
command.Connection.Close()
Clear()
lblMessage.Text = "You have been successfully added into our records"
Catch ex As Exception
lblMessage.Text = "Something has gone wrong with adding you to our records, please double check everything as we want you to become a member."
End Try
End Sub
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
txtFirstname.Text = table.Rows(0).Field<string>("Firstname")
txtFirstname.DataBind()
txtSurname.Text = table.Rows(0).Field<string>("Surname")
txtSurname.DataBind()
txtGender.Text = table.Rows(0).Field<String>("Gender")
txtGender.DataBind()
txtAge.Text = table.Rows(0).Field<Integer>("Age")
txtAge.DataBind()
txtAddress1.Text = table.Rows(0).Field<String>("Address1")
txtAddress1.DataBind()
txtAddress2.Text = table.Rows(0).Field<String>("Address2")
txtAddress2.DataBind()
txtCity.Text = table.Rows(0).Field<String>("City")
txtCity.DataBind()
txtPhone.Text = table.Rows(0).Field<Integer>("Phone Number")
txtPhone.DataBind()
txtMobile.Text = table.Rows(0).Field<Integer>("Mobile Number")
txtMobile.DataBind()
txtEmail.Text = table.Rows(0).Field<String>("Email")
txtEmail.DataBind()
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub
So I'm just wondering what I've written wrong or if I should be using other code instead of what I have here, I know I should be using C# but I just got the hang of vb so, hopefully I can just start using C# after this project.
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
dim objDV as dataview = table.defaultview
txtFirstname.Text = objDV(0)("Firstname").tostring
txtSurname.Text = objDV(0)("Surname").tostring
' Fill all other text boxes following above lines
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub

Error in vb.net code in INSERT INTO

When I try to insert data in these three field gets an error saying error in INSERT INTO Statement.
but when a save in only the first field sname it gets added but when adds other two gets this error
I am getting an exception in INSERT INTO Statement check below
any advice?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" + "VALUES ('" & txtname.Text & "','" & txtuser.Text & "','" & txtpass.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
con.Close()
End With
MsgBox("User Registered")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The word PASSWORD is a reserved keyword in JET-SQL for Microsoft Access. If you have a column with that name you should encapsulate it with square brackets
"INSERT INTO admin (sname,username,[password])" &% _
"VALUES ('" & txtname.Text & "','" & txtuser.Text & _
"','" & txtpass.Text & "');"
That's the reason of the syntax error, however let me tell you that building sql commands concatenating strings is a very bad practice. You will have problems when your values contain single quotes and worst of all, your code could be used for sql injection Attacks
So your code should be changed in this way
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" & _
"VALUES (?, ?, ?)"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.Parameters.AddWithValue("#p1", txtname.Text)
.Parameters.AddWithValue("#p2", txtuser.Text)
.Parameters.AddWithValue("#p3", txtpass.Text)
.ExecuteNonQuery()
con.Close()
End With
also your use of the object OleDbConnection doesn't follow a good pattern. In case of exception you don't close the connection and this could be a problem in reusing the connection in subsequent calls.
You should try to use the Using statement
Using connection = New OleDb.OleDbConnection()
connection.ConnectionString = dbprovider
connection.Open()
.....
' rest of command code here '
' No need to close the connection
End Using
in this way, also if you get an exception the OleDbConnection will be closed and disposed without impact on system resource usage.