error while inserting the audio file in database - asp.net

str = "INSERT INTO reg (Name,ContentType,Data) values (?,?,?)"
Try
cmd = New OleDbCommand(str, dbcon)
cmd.Parameters.AddWithValue("Name", "chillax")
cmd.Parameters.AddWithValue("ContentType", "audio")
cmd.Parameters.AddWithValue("Data", System.IO.File.ReadAllBytes("E:\chillax.wav"))
cmd.ExecuteNonQuery()
MsgBox("inserted")
Catch ex As Exception
MsgBox("notWorking")
End Try
well, above code is not working(Data - binary datatype)
can anyone know wats wrong in tat code

Related

How to do Commit/rollback in sql server using VB.net

I'm working on an asp.net application which involves sql server as database. After writing huge function in vb.net, I had to select , insert and update different tables using one n other. I realized that, if all of this executed in one go then its a win win situation. If all of this doesn't go well then it would create a huge mess.
When we do DML operations in Oracle, we had to
commit;
rollback;
after every DML operation. My question is how do we do the same thing in sql server using VB.net.
My search leads to write a procedure #sql server. Inseration and delation will be done via sorted procedure. But I want it as normal operations like
SqlCommand("some query", connection")
Is it possible to do commit or rollback without using sorted procedures??
Thanks in advance!
You can also use a TransactionScope, which gives a bit cleaner code than managing transactions yourself.
Using transaction As NewTransactionScope()
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
command.ExecuteNonQuery()
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
command.ExecuteNonQuery()
End Using
' If we do not run Commit(), e.g. an error occurs before we get here,
' the transaction will automatically roll back when we leave the Using block below
transaction.Commit()
End Using
You should use SqlTransaction.
Here is a shameless copy-paste from MSDN:
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
Dim transaction As SqlTransaction
' Start a local transaction
transaction = connection.BeginTransaction("SampleTransaction")
' Must assign both transaction object and connection
' to Command object for a pending local transaction.
command.Connection = connection
command.Transaction = transaction
Try
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
command.ExecuteNonQuery()
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
command.ExecuteNonQuery()
' Attempt to commit the transaction.
transaction.Commit()
Console.WriteLine("Both records are written to database.")
Catch ex As Exception
Console.WriteLine("Commit Exception Type: {0}", ex.GetType())
Console.WriteLine(" Message: {0}", ex.Message)
' Attempt to roll back the transaction.
Try
transaction.Rollback()
Catch ex2 As Exception
' This catch block will handle any errors that may have occurred
' on the server that would cause the rollback to fail, such as
' a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
Console.WriteLine(" Message: {0}", ex2.Message)
End Try
End Try
End Using
End Sub

Try Catch Exception running SQL Query Twice

This function seems to be running the SQL query twice, any idea why?
When I run an insert SQL query it inserts the data but also brings back this error:
Violation of PRIMARY KEY constraint 'PK__SD_T_Cod__143F51C51BFD2C07'.
Cannot insert duplicate key in object 'dbo.SD_T_Code'. The duplicate
key value is (t-503).
This seems to tell me that it is running the SQL twice, it gets inserted the first time, but the second time it doesn't insert because the id already exists (it got created with the first insert)
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim connStr As String = ConfigurationManager.ConnectionStrings("dbConnect").ConnectionString
Dim con As New SqlConnection(connStr)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
'resultSQL.Text = ex.Message
Return False
Finally
resultSQL.Text = "Successfully Saved"
con.Close()
con.Dispose()
End Try
End Function
End Class

Attempting to load a datatable - Operation is not valid due to the current state of the object

I'm trying to connect & query an Oracle DB and load the results into a datatable but I keep getting the 'operation is not valid due to the current state of the object' error for the code below:
Using conn As New OracleConnection(oradb)
Try
cmd = New OracleCommand()
da = New OracleDataAdapter(cmd)
dteDTK = New DataTable()
conn.Open()
cmd.CommandText = "SELECT * FROM TABLE1"
cmd.CommandType = CommandType.Text
da.Fill(dteDTK)
Catch ex As OracleException
MessageBox.Show(ex.Message.ToString())
Finally
conn.Close()
conn.Dispose()
End Try
End Using
The error throws on the 'da.Fill(dteDTK)' command. What am I missing here?
You are not assigning the Connection to the Command. I would imagine that you need to do this on OracleCommand:
cmd.Connection = conn
Otherwise, you are executing a SQL statement on a command that has no connection associated.

second ExecuteReader() doesn't work

I have a code which checks the validity of user and then, if a user is valid it inserts certain values in the database.
My problem is when After I query my database to check if a user is valid and after that i try to pass the additional value to its account the flow stops when I invoke ExecuteReader() for the second time.
There is no error, or anything like that. I tried to substitute ExecuteReader() with ExecuteNoneQuery but still it's not working. I tried all the query in mysql command prompt they are working perfectly. I really can't understand what am I doing wrong there. Can anyone help me please?
Here is the code:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE SE_ID = " & Id.Text
Dim smd = New MySqlCommand(stquery, myconn)
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
errorUser.Visible = True
Else
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
Dim Myreader2 As MySqlDataReader
'smd.ExecuteNonQuery()'
'THE CODE STOPS HERE'
Myreader2 = smd2.ExecuteReader()
'Myreader2.Read()'
MsgBox("The BACKUP INFORMATION HAS BEEN SAVED")
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Because your second query is an update, not a select, you need to execute it using the ExecuteNonQuery method. Your commented-out code shows an attempt to call ExecuteNonQuery but on the wrong command object (smd when it should be smd2). Try something like this instead:
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd2.ExecuteNonQuery()
The ExecuteNonQuery method returns the number of rows updated as an int value, so you can capture it if it's valuable to you. In your case it's probably not, but here's how you'd check anyway:
int rowsAdded = smd2.ExecuteNonQuery();
if (rowsAdded == 1) {
// expected this
} else {
// didn't expect this
}
Finally, concatenating strings to build SQL commands can leave you vulnerable to SQL Injection attacks. Please take a look at using parameterized queries. There's a decent example here.
If you want to execute nested Reader, you have to create another connection. You need somethig like
smd2 = New MySqlCommand(stquery2, myconn2)' myconn2 is another connection
OR
Set "MultipleActiveResultSets=True in your connection string.
Also, use ExecuteNonQuery() for Inserting
Dim name As String = myreader("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES ('" & name & "', '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd.ExecuteNonQuery()
Please use Parameterized query to avoid SQL Injection
The logic is that you need to close your first reader (myreader) before executing another reader (MyReader2) on the same connection.

database update sql not affecting database

i have this code to update a database, but when ever i run it with the right data, it executes without errors but the databse is not update
Dim conn As New SqlClient.SqlConnection(My.Resources.conn_str)
Dim SQL As String = "Update vehicle SET make=#make,reg_no=#reg_no,model=#model,year=#year,type=#type,last_service=#last_service Where (id = #id)"
conn.Open()
Try
Dim cmd As New SqlClient.SqlCommand(SQL, conn)
Try
cmd.Parameters.AddWithValue("#make", strMake)
cmd.Parameters.AddWithValue("#reg_no", strRegnNum)
cmd.Parameters.AddWithValue("#model", strModel)
cmd.Parameters.AddWithValue("#year", intYear)
cmd.Parameters.AddWithValue("#type", strType)
cmd.Parameters.AddWithValue("#last_service", LastService)
cmd.Parameters.AddWithValue("#id", ID.ToString)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
Return ex.Message
End Try
Catch ex As Exception
Return ex.Message
Finally
conn.Dispose()
End Try
can anyone help me with the reason its not working, as i don get an error message?
thanks
EDIT
i replaced the cmd.ExecuteNonQuery() with
Dim intAffected As Integer = cmd.ExecuteNonQuery()
Debug.Print(intaffected)
and i get 1 in the output window
A few thoughts:
If you have access to SQL Profiler, you can see the query, the values, the result, any triggers, any transactions, etc. This is the easiest way to identify what is going on.
If you don't have access to Profiler, update your query to include the OUTPUT clause, and return the values from inserted.* and deleted.* into a SqlDataReader using ExecuteReader. Check the results.
If the id is an int, don't use ID.ToString() on the parameter.AddWithValue. Use the integer itself, as the AddWithValue method with a string value could cause the ID parameter to be configured as a varchar/nvarchar.

Resources