Saving document file in SQL Server database using vb.net - sql-server

Please I need your help. I am trying to save a file in a SQL Server database, but it is showing this error
Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
Here is my code
Private Sub Button70_Click(sender As Object, e As EventArgs) Handles Button70.Click
fna = content.Text
fna.Split("\")
ffn = fna.Last.ToString
conn.Open()
Dim com As New SqlCommand
com.Connection = conn
com.CommandText = "insert into meeting (Date_Entry, Title, Chairperson, Venue, File_Name, [Content]) values( '" & date5.Text & "', '" & title.Text & "', '" & cp.Text & "', '" & vn.Text & "', '" & f_name.Text & "', '#[Content]')"
With com.Parameters
.AddWithValue("Content", SqlDbType.VarBinary).Value = File.ReadAllBytes(content.Text)
End With
com.ExecuteNonQuery()
conn.Close()
MsgBox("File saved")
content.Clear()
End Sub
Private Sub Button25_Click(sender As Object, e As EventArgs) Handles Button25.Click
'// open dilogue to add file to save
If op.ShowDialog = Windows.Forms.DialogResult.OK Then
content.Text = op.FileName
End If
End Sub

You should use #Content instead of #[Content] in your query string.

Related

I want to update my data of my database in VB.net but I get Error Syntax

This is my problem:
When I click update button, I don't know how to fix this error:
My Error Message is:
"Error: syntax error in union query"
This is my code:
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Try
Dim cmd As OleDbCommand
Dim sql As String
sql = "(UPDATE tblUsers SET Username = '" & txtUserName.Text & "', Password = '" & txtUserPassword.Text &
"', Usertype = '" & cbousertype.Text & "', WHERE UserID = '" & txtUserID.Text & "');"
cmd = New OleDbCommand(sql, Conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
End Sub
Is it wrong?
Now my problem has been solved thank you very much
i changed my code to use a parameters and then it work
Now my code is :
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE tblUsers SET Username=?, [Password]=?, Usertype=? where UserID=?"
cmd = New OleDbCommand(sql, Conn)
cmd.Parameters.AddWithValue("#p1", txtUserName.Text)
cmd.Parameters.AddWithValue("#p2", txtUserPassword.Text)
cmd.Parameters.AddWithValue("#p3", cbousertype.Text)
cmd.Parameters.AddWithValue("#p4", txtUserID.Text)
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Updated", MsgBoxStyle.Information, "Updated")
ShowUser()
End Sub

Visual Basic get data from a combobox

My code is now this, as i forgot to add the connection to my database after i updated the table, still doesnt work though
Private Sub cmdRegistar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegistar.Click
myConnToAccess = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = 'D:\PAP\LoginForm\LoginForm\bin\debug\login.mdb'")
myConnToAccess.Open()
Try
Dim x As String
Dim str As String
x = ComboBox1.Text
str = "UPDATE UserTable set Password = '" & txtPass.Text & "' where Username = '" & x & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnToAccess)
myConnToAccess.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
So as you can see the code doesnt have any errors, it compiles and runs just fine, it just doesnt work, the combobox values come from the same database of what i'm trying to do with the command update. All my others conections work just fine, my add, search.
When are you actually passing str to your database? Shouldn't you have something like str.Execute or something in there? Aside from that, you also have an error in this line:
str = "UPDATE UserTable set Password" & txtPass.text & "where Username= '" & x & "'"
It should be:
str = "UPDATE UserTable set Password = '" & txtPass.text & "' where Username = '" & x & "'"
Password is a reserved word, so try this:
str = "UPDATE UserTable set [Password] = '" & txtPass.Text & "' where Username = '" & x & "'"

Query will not update SQL Server

In the below code, my second query will not insert into the SQL database, but the first one will update. I can copy the query (from the msgbox i added for testing) and paste it in SQL Server Management Studio, and it will execute fine. I also do not get any error messages back from SQL, though i'm not sure if that code is correct (it was copied + pasted from another source). Also, can i simplify the code to pass both queries at the same time?
Dim Conn As New System.Data.SqlClient.SqlConnection 'sql server datastream connection
Dim Cmd As New System.Data.SqlClient.SqlCommand 'sql command vars
Dim SqlQuery As String 'string var used to hold various SQL queries
Dim data As System.Data.SqlClient.SqlDataReader 'datareader object variable
Dim MVDataset As New DataSet
Dim MVDatatable As DataTable
Dim MVDatarow As DataRow
Private Sub MVUpdateButton_Click(sender As Object, e As EventArgs) Handles MVUpdateButton.Click
vbyn = MsgBox("Are you sure you want to update Tally Sheet Master Variables?" & vbCrLf & vbCrLf & "Changes to these variables will change the functionality of the Tally Sheet!", vbYesNo, )
Try
Select Case vbyn
Case vbNo
GoTo MVTableUpdateBypass
Case vbYes
'get new data from textboxes
Vers = TextBox1.Text
If TextBox2.Text = True Then
Testing = 1
Else
Testing = 0
End If
FlatFeeCharge = TextBox3.Text
PrepricingCharge = TextBox4.Text
SendMailAcct = TextBox5.Text
SendMailPW = TextBox6.Text
TestingEmail = TextBox7.Text
PrePricingEmail = TextBox8.Text
ImperataEmail = TextBox9.Text
'update existing active row to mark inactive
SqlQuery = "Update MasterVars set Active = 0 where PKEY = " & PKEY & ";"
MsgBox(SqlQuery)
If Conn.State = ConnectionState.Closed Then
Conn.ConnectionString = "Data Source=SQL01;Initial Catalog=TallySheet;Integrated Security=SSPI;"
End If
Conn.Open()
Dim MVDataAdapter As New SqlDataAdapter(SqlQuery, Conn)
Dim MVUpdateCommand As SqlCommand
MVUpdateCommand = New SqlCommand(SqlQuery)
MVDataAdapter.UpdateCommand = MVUpdateCommand
'insert new active row
SqlQuery = "Insert into MasterVars (Vers, Testing, FlatFeeCharge, PrePricingCharge, SendMailAcct, SendMailPW, TestingEmail, PrePricingEmail, ImperataEmail, DTS, UserName, Active) Values (" & "'" & Vers & "', " & Testing & ", '" & FlatFeeCharge & "'" & ", '" & PrepricingCharge & "'" & ", '" & SendMailAcct & "'" & ", '" & SendMailPW & "'" & ", '" & TestingEmail & "'" & ", '" & PrePricingEmail & "'" & ", '" & ImperataEmail & "'" & ", '" & Date.Now & "'," & "'QGDOMAIN\" & Environment.UserName & "'," & 1 & ");"
MsgBox(SqlQuery)
Dim MVInsertCommand As SqlCommand
MVInsertCommand = New SqlCommand(SqlQuery)
MVDataAdapter.InsertCommand = MVInsertCommand
MVDataAdapter.Fill(MVDataset, "MasterVars")
End Select
Catch ex As SqlException
Dim i As Integer
Dim errormessages As String
errormessages = ""
For i = 0 To ex.Errors.Count - 1
errormessages = errormessages & " " & ("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
Console.WriteLine(errorMessages.ToString())
End Try
'reload form with updated variables
Conn.Close()
Conn.Dispose()
MVTableUpdateBypass:
End Sub
The Fill method of the SqlDataAdapter executes the SelectCommand not the UpdateCommand or the InsertCommand. In any case these two commands (and the DeleteCommand) are executed when you call the Update method of the adapter.
Moreover the Update method runs the commands looking for rows changed/added/deleted in the DataTable/DataSet retrieved by the SelectCommand and works only for those rows.
But you don't need an SqlDataAdapter to execute your two queries. You should simply construct an SqlCommand with both texts separated by a semicolon and call ExecuteNonQuery
SqlQuery = "Update MasterVars set Active = 0 where PKEY = #key;" & _
"Insert into MasterVars (Vers, Testing, .....) VALUES (#p1, #o2, ....)"
Using Conn = New SqlConnection("Data Source=SQL01;......")
Using cmd = New SqlCommand(SqlQuery, Conn)
Conn.Open()
cmd.Parameters.Add("#key", SqlDbType.Int).Value = PKEY
cmd.Parameters.Add("#p1", SqlDbType.NVarChar).Value = vers
cmd.Parameters.Add("#p2", SqlDbType.Int).Value = testing
... and so on with other parameters ....
cmd.ExecuteNonQuery()
End Using
End Using
In this incomplete example (too many parameters to write down) I have concatenated the two sql texts in a single string and prepared it with parameter placeholders. Then I build the parameter collection with the exact datatypes required by your table and finally call ExecuteNonQuery to run everything on the database side.
Notice that is not needed to keep global objects like the connection or the command. It is always better to create a local variable, use and destroy it when done. In particular disposable objects like the connection and the command should always created in a Using block

How to set the code to update the table in database

I'm making a system by using Visual Studio Express 2012 and use the Microsoft SQL Server that already have in visual studio I think. My problem is, when i'm trying to run my system,an error occur said "Operator '&' is not defined for types 'String' and 'System.Windows.Forms.DataGridView'." This is my code.
Imports System.Data.SqlClient
Public Class Registration
Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\user_PC\Desktop\For FYP\Computer Lab Requirement System\FYP3\FYP3\FYP.mdf;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Private Sub Registration_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cmd.Connection = cn
End Sub
Private Sub btnRegisterL_Click(sender As Object, e As EventArgs) Handles btnRegisterL.Click
If txtIDL.Text <> "" And txtUsernameL.Text <> "" And txtPasswordL.Text <> "" Then
cn.Open()
cmd.CommandText = "update info set id = '" & txtIDL.Text & "',user = '" & txtUsernameL.Text & "',pass = '" & txtPasswordL.Text & "'where id = '" & Form1.DataGridView1 & "' "
cmd.ExecuteNonQuery()
cn.Close()
txtIDL.Text = ""
txtUsernameL.Text = ""
txtPasswordL.Text = ""
End If
End Sub
End Class
I'm glad if there is some one could help me to explain and teach me about whats wrong with my coding above. I'm new in this thing. Thanks. :)
You could hold the Primary Key of your data in your GridView in one of the columns and then use that in your query, instead of the below line that you have:
"'where id = '" & Form1.DataGridView1 & "' "

Getting an exception while accessing an Access database

I need to insert a row into the Access table. I have been getting
object reference not set to instance of an object
My code is:
Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim strconstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb"
Dim objcon As OleDb.OleDbConnection
objcon = New OleDb.OleDbConnection(strconstring)
Dim objcommand As OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Try
objcon.Open()
Dim command As String
command = "insert into Artists(Artist, Company, Sales )" _
& " values('" & ArtistBox.Text & "', '" _
& TextBox2.Text & "', " & TextBox3.Text & ")"
objcommand = New OleDb.OleDbCommand(command, objcon)
da.InsertCommand.CommandText = command
da.InsertCommand.ExecuteNonQuery()
Catch exceptionobject As Exception
MessageBox.Show(exceptionobject.Message)
Finally
objcon.Close()
End Try
End Sub
Your connection string is a bit of a mess, so that may be causing the problem. Use EITHER...
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;
...OR...
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;

Resources