Image not inserted into the SQL Server database - sql-server

I am a beginner here may I know how to resolve my problem?
I create a program to save images in SQL Server, but this is not working.
Error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Thank you and hopefully for your response guys!
Here is the code:
Imports System.Data.SqlClient
Imports System.IO
Public Class Form5
Dim connection As New SqlConnection("Server=kohyoung-aoi\sa; Database = testDB; Integrated Security = true")
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim command As New SqlCommand("insert into Table_Image1 (Name, Description, Barrowed, Returned, Picture) values (#Name, #Description, #Barrowed, #Returned, #Picture)", connection)
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = Txt1.Text
command.Parameters.Add("#Description", SqlDbType.VarChar).Value = Txt2.Text
command.Parameters.Add("#Barrowed", SqlDbType.VarChar).Value = txt3.Text
command.Parameters.Add("#Returned", SqlDbType.VarChar).Value = txt4.Text
command.Parameters.Add("#Picture", SqlDbType.Image).Value = ms.ToArray()
connection.Open()
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("Image Inserted")
Else
MessageBox.Show("Image not Inserted")
End If
End Sub
I expected to run in normal condition and the output is to save all images into SQL Server.

Related

VB.NET SQL conversion error when trying to read data

I'm trying to get data from a database but keep getting the following error.
Conversion failed when converting the varchar '102A' to data type int
The database table has 3 columns UserID, UserName, UserInfo, all of them defined as type varchar.
There is also a user in the table with ID 102A.
I'm trying to get the Username of the User with ID 10307.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim datareader As SqlDataReader
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True"
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM Users WHERE UserID = 10307"
datareader = cmd.ExecuteReader
datareader.Read()
MsgBox(datareader.GetValue(2))
datareader.Close()
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I also tried to change datareader.GetValue to datareader.GetString but I get the same error.
Can anyone help me please, I've been stuck for days now...
Thank you

Simple select query not working with vb.net while delete query works fine

I am writing a simple SQL Server query operation through vb.net application. I am having some strange problems.
This line is giving error:
dr = cmd.ExecuteReader()
This is giving me error "Invalid column name abhishek." Here abhishek is the data I am providing in TextBox1.Text. I am not able to think of any mistake by my side as this is a simple query. I am able to run other queries, like delete queries, on same table in a different form, so its not a database problem.
Any clue what's going wrong?
reginfo is the table name. name is one of the fields.
My complete code is below:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form9
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cmd.CommandText = "select * from reginfo where name=" + (TextBox1.Text) + ""
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader() '<<< This line is creating problem
If dr.Read() Then
TextBox2.Text = dr(0).ToString()
End If
con.Close()
End Sub
Private Sub Form8_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=ABHISHEK-PC\SQLEXPRESS;Initial Catalog=locserver;Integrated Security=True;Pooling=False"
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
End Sub
End Class
if the name field is a text field then you need to enclose your textbox in single quotes, but this is bad advice to give. The only good approach to this kind of situations is through a parameterized query
cmd.CommandText = "select * from reginfo where name=#name"
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader()
Also, do not keep global objects like a connection or a command. It is always a good practice to instantiate a connection as late as possible and close it as soon as possible, better inside a Using block
Using con = New SqlConnection(...connection string here....)
Using cmd = New SqlCommand("select * from reginfo where name=#name", con)
con.Open()
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Using dr = cmd.ExecuteReader
'.... do you reading
End Using
End Using
End Using
In this way the connection is kept open for the minimum time possible and, also in case of exceptions is closed and disposed appropriately.

Executing stored procedure of sql client. By the method i am habituated in

I used to follow this method to execute SQL Server agent queries
Public connection As New SqlConnection(connectionstring)
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim sqlquery As String = "insert into tbluserdetails (username,password,usertype) values (#username,#password,#usertype)"
Dim cmd As New SqlCommand(connectionstring, connection)
cmd.Parameters.AddWithValue("#username", txtusername.Text)
cmd.Parameters.AddWithValue("#password", txtpassword.Text)
cmd.Parameters.AddWithValue("#usertype", cbousertype.Text)
Try
connection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
connection.Close()
End Try
End Sub End Class
Now I want to execute the stored procedure sp_saurav that has 5 parameters. Using same method is it possible? I googled for this but there are very different codes shown.
I would be grateful if someone could help me execute stored procedure with identical code as shown above.
You have to set the CommandType property of the SqlCommand object to the value StoredProcedure and set the procedure name as the value for CommandText property.
Dim connString As String = "connectionstring"
Dim sqlquery As String = "procedure_name"
Using conn As New SqlConnection(connString)
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = sqlquery
cmd.Parameters.AddWithValue("#param1", value1)
cmd.Parameters.AddWithValue("#param2", value2)
cmd.Parameters.AddWithValue("#param3", value3)
cmd.Parameters.AddWithValue("#param4", value4)
cmd.Parameters.AddWithValue("#param5", value5)
cmd.ExecuteNonQuery()
End Using

how to get the last userID from a database into textbox in asp.net

Thanks I used the MAX statement and it doesn't return an error but still don't understand why it isn't working. My code is shown below:
Protected Sub txtuserID_TextChanged(sender As Object, e As System.EventArgs) Handles txtuserID.TextChanged
Dim strConnection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=E:\LostPropertyProject\App_Data\LostPropertyDatabase.mdf;Integrated Security=True;User Instance=True"
'Establish SQL Connection
Dim con As New SqlConnection(strConnection)
'Open database connection to connect to SQL Server
con.Open()
'Data table is used to bind the resultant data
Dim dtusers As New DataTable()
'Create a new data adapter based on the specified query.
Dim comm As New SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM tblUser"
comm.Connection = con
Dim MaxUserID As Object = comm.ExecuteScalar()
con.Close()
End Sub
Also, I want the userID to be displayed in the textbox as soon as the page loads. How do I go about doing that? and thank you to everyone who replied to my question :) much appreciated
SELECT MAX(UserId) FROM User
This will give you the latest user id from the table.

Read from a visual basic api an SQL Server stored procedure

Can someone point me in the right direction? I have not been able to find documentation to help me build a vb api that can read from a SQL Server stored procedure. I currently have an api that works, I was able to test my controller and the methods (GET, POST, ) work. Please let me know how can I read from a .sql file.
The code below is in Calendar Model - Calendar.vb
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sqlFile As String = "C:\temp\test.sql"
Dim sqlText = File.ReadAllText(sqlFile)
Dim connStr = "Server=.\SQLEXPRESS; Database=testing; Integrated Security=SSPI"
Dim conn = New SqlConnection(connStr)
Dim sqlCmd = New SqlCommand(sqlText, conn)
Try
conn.Open()
sqlCmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Something went wrong: " & ex.Message)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End Sub
End Class
If the test.sql execute a run of stored procedure and if it's return a table you can read as this :
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
End While
If it's return one value use this
intValue =Convert.ToInt32(sqlCmd.ExecuteScalar())

Resources