i am trying to upload an image and saving image name in database as the session name with extension .jpg
i got problem that only the image name saved in database not the extension. i am using this code
Dim strPath As String = Server.MapPath("~/UserPics/")
If AsyncFileUpload1.HasFile Then
AsyncFileUpload1.SaveAs(strPath & Session("UserName").ToString() & ".jpg")
lblUploadMessage.Text = "You uploaded " + AsyncFileUpload1.FileName
con.Open()
Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & "')", con)
objCmd.ExecuteNonQuery()
con.Close()
Else
lblUploadMessage.Text = "Please select an image first"
Return
End If
You are not inserting the same string you are saving, you have to add the extension see below. Also, add the extension from the file posted instead of hard-coding:
Dim objCmd As New SqlCommand("insert into regist(image1) values ('" & _
Session("UserName").ToString() & _
System.IO.Path.GetExtension(AsyncFileUpload1.PostedFile.FileName) & "')", con)
Please change you code to using parameters in order to prevent SQL Injection attacks:
Dim objCmd As New SqlCommand(con)
Dim sql As String = "insert into regist(image1) values (#image)"
Dim param(1) As SqlParameter
param(0) = New SqlParameter("#image", SqlDbType.VarChar)
param(0).Value = Session("UserName").ToString() & _
System.IO.Path.GetExtension(AsyncFileUpload1.PostedFile.FileName);
objCmd.Parameters.AddRange(param)
objCmd.ExecuteNonQuery()
con.Close()
Change
Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & "')", con)
to
Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & ".jpg" & "')", con)
Related
I have encountered this "Invalid attempt to call Read when the reader is closed." error and I have tried to solve it for so many times. I think the connection is open but it still shows this error. Can somebody tell me why?
Here is the code:
Dim ConnComName As String
Dim sqlConnComName As SqlConnection
Dim sqlCmdComName As SqlCommand
Dim sqlComName As String
ConnComName = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
sqlComName = "Select COUNT(*) from TicketDetails where Company = '" & Company.SelectedValue & "' AND Priority = '" & Priority.SelectedValue & "' AND Application = '" & Application.SelectedValue & "' AND Creator = '" & Creator.Text & "' AND Status = '" & Status.SelectedValue & "' AND Module = '" & [Module].SelectedValue & "' AND Category = '" & Category.SelectedValue & "' AND IssueType = '" & IssueType.SelectedValue & "' AND IssueDescription = '" & IssueDescription.Text & "' "
sqlConnComName = New SqlConnection(ConnComName)
sqlConnComName.Open()
sqlCmdComName = New SqlCommand(sqlComName, sqlConnComName)
Dim sqlReader_ComName As SqlDataReader = sqlCmdComName.ExecuteReader()
While sqlReader_ComName.Read()
If sqlReader_ComName.GetValue(0) < 1 Then
ElseIf sqlReader_ComName.GetValue(0) > 0 Then
Dim CompanyName As String
Dim ConnComName01 As String
Dim sqlConnComName01 As SqlConnection
Dim sqlCmdComName01 As SqlCommand
Dim sqlComName01 As String
ConnComName01 = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
sqlComName01 = "Select Company from TicketDetails Where Company = '" & Company.SelectedValue & "' AND Priority = '" & Priority.SelectedValue & "' AND Application = '" & Application.SelectedValue & "' AND Creator = '" & Creator.Text & "' AND Status = '" & Status.SelectedValue & "' AND Module = '" & [Module].SelectedValue & "' AND Category = '" & Category.SelectedValue & "' AND IssueType = '" & IssueType.SelectedValue & "' AND IssueDescription = '" & IssueDescription.Text & "' "
sqlConnComName01 = New SqlConnection(ConnComName01)
sqlConnComName01.Open()
sqlCmdComName01 = New SqlCommand(sqlComName01, sqlConnComName01)
Dim sqlReader_ComName01 As SqlDataReader = sqlCmdComName01.ExecuteReader()
While sqlReader_ComName01.Read()
CompanyName = sqlReader_ComName01.GetValue(0)
' end while ComName01
End While
sqlReader_ComName01.Close()
sqlCmdComName01.Dispose()
sqlConnComName.Close()
End If
End While
sqlReader_ComName.Close()
sqlCmdComName.Dispose()
sqlConnComName.Close()
As has been said in the comments, the reason you are getting the error is because you are using a shared SqlConnection, which you close at the end of your inner loop, although there is actually no good reason to share a connection object here; .NET uses connection pooling behind the scenes, so there is little or no downside to creating new connection objects for every command, and it can often save confusion like this. You should also use Using blocks to ensure that all your managed resources are disposed of correctly and at the right time. Finally, and I can't stress this enough, use Parameterised queries, your code is vulnerable to injection, malformed SQL, type errors and will be unable to make use of query plan caching.
Although you have two loops in your code, all you ever do in those loops is to assign a value to a string:
While sqlReader_ComName01.Read()
CompanyName = sqlReader_ComName01.GetValue(0)
End While
So with every inner and outer loop, you overwrite the previous value, making all loops other than the last completely pointless. Since your SQL has no order by, you also have no idea which order the results will come in, so the "last" record could be any record here.
You don't need two loops here, if you only want a single value from the database, just select single value, there is no point returning 500 records if you are only going to use one.
So with all these changes your code might look something like this (forgive any syntax errors, it is about 8 years since I last wrote any VB.net)
Dim CompanyName As String
'Change SQL to only select 1 record, use an order by, and use parameters
Dim sql As String = "Select TOP (1) Company from TicketDetails Where Company = #Company AND Priority = #Prioirty AND Application = #Application AND Creator = #Creator AND Status = #Status AND Module = #Module AND Category = #Category AND IssueType = #IssueType AND IssueDescription = #IssueDescription ORDER BY Company"
' Create new conneciton in Using block
Using connection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnString").ConnectionString)
'Create new command in using block
Using command As SqlCommand = New SqlCommand(sql, connection)
'Add parameters to command, change your data types and lengths as necessary
command.Parameters.Add("#Company", SqlDbType.VarChar, 50).Value = Company.SelectedValue
command.Parameters.Add("#Priority", SqlDbType.VarChar, 50).Value = Priority.SelectedValue
command.Parameters.Add("#Application", SqlDbType.VarChar, 50).Value = Application.SelectedValue
command.Parameters.Add("#Creator", SqlDbType.VarChar, 50).Value = Creator.Text
command.Parameters.Add("#Status", SqlDbType.VarChar, 50).Value = Status.SelectedValue
command.Parameters.Add("#Module", SqlDbType.VarChar, 50).Value = [Module ].SelectedValue
command.Parameters.Add("#Category", SqlDbType.VarChar, 50).Value = Category.SelectedValue
command.Parameters.Add("#IssueType", SqlDbType.VarChar, 50).Value = IssueType.SelectedValue
command.Parameters.Add("#IssueDescription", SqlDbType.VarChar, 50).Value = IssueDescription.Text
'Open the connection
connection.Open()
'Create the data reader
Using reader As SqlDataReader = command.ExecuteReader()
'If the reader.Read() method returns true, then there is a record, so read it and assign it to the variable
If reader.Read()
CompanyName = reader.GetString(0);
End If
End Using
End Using
End Using
This is my first time writing in VB.Net for aspx pages.
The problem I having is that the parameter is not going into the query at the line for cmd.Parameters.Add.
The error I am getting is
No value given for one or more required parameters.
on the line
reader = cmd.ExecuteReader;
I have tried:
Adding the PARAMETERS at the top of the query like I have shown;
Removing and Adding [] around the parameter;
Changing OleDbType.Integer to OleDbType.SmallInt or OleDbType.BigInt
I know the query works as I can place it into MS Access and will run once I add the parameter. But not when I run it in Visual Studio.
Dim reader As OleDbDataReader
Dim cmd As OleDbCommand
Dim SQL As String = "PARAMETERS [#ID] Long; " &
"SELECT tblField.FieldName, " &
"tblField.FieldCaption, " &
"tblField.FieldMinCharNum, " &
"tblField.FieldMaxCharNum, " &
"tblField.FieldDefault, " &
"tblField.FieldSection, " &
"tblField.FirstQuestion, " &
"tblField.FieldDescription, " &
"tblField.FieldRegEx " &
"FROM tblField " &
"WHERE tblField.FieldID = [#ID];"
cmd = New OleDbCommand(SQL, Connection.Connection)
cmd.Parameters.Add("[#ID]", OleDbType.Integer).Value = ID
reader = cmd.ExecuteReader
I have a work around to make it work by just pre-inserting the parameter into the SQL string. But I want to make this work for other areas of the page that are yet to be written. Where user inputs are coming back into database so inputs are sanitised.
OLEDB doesn't use # to identify parameters. It uses ? and allocates parameters in the order they appear in the SQL amend your code to...
Dim reader As OleDbDataReader
Dim cmd As OleDbCommand
Dim SQL As String = "SELECT tblField.FieldName, " &
"tblField.FieldCaption, " &
"tblField.FieldMinCharNum, " &
"tblField.FieldMaxCharNum, " &
"tblField.FieldDefault, " &
"tblField.FieldSection, " &
"tblField.FirstQuestion, " &
"tblField.FieldDescription, " &
"tblField.FieldRegEx " &
"FROM tblField " &
"WHERE tblField.FieldID = ?"
cmd = New OleDbCommand(SQL, Connection.Connection)
cmd.Parameters.Add("?", OleDbType.Integer).Value = ID
reader = cmd.ExecuteReader
I don't understand why your mentioning SQL are you retrieving the data from SQL Query or are you going to insert data into the table.
your using Dim cmd As OleDbCommand means use to insert the input values into the database like see below sample code.
query = "INSERT INTO ds.students (ID,NAME,PIC)" & _
"VALUES (#ID,#NAME,#PIC);"
Dim cmd As OracleCommand = New OracleCommand(query, con)
cmd.Parameters.Add("#ID", Convert.ToInt32(TextBox1.Text))
cmd.Parameters.Add("#NAME", Convert.ToString(TextBox2.Text))
cmd.Parameters.Add("#PIC", arrImage)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
you can try this also
Using cn As OracleConnection = New OracleConnection(connectionString)
cn.Open()
Using cmd As OracleCommand = New OracleCommand()
Const sql As String = "Insert into test_table (val1, val2) values (:var1, :var2)"
cmd.Connection = cn
cmd.Parameters.Add(New OracleParameter("var1", TxtField1.Text))
cmd.Parameters.Add(New OracleParameter("var2", TxtField2.Text))
cmd.CommandText = sql
cmd.ExecuteNonQuery()
End Using
End Using
if you want to insert the values into the database change your code according to given samples.
Hope this will help you.
I'm trying to display information on a piece of equipment the idea is that the user will type in an ID in the textbox and it will display the information on a grid view:
Dim ID As String = TxtSearch.Text
Dim cmd As SqlCommand
Dim ds As String = "Select * from Medical_Equipment where AssetID='" & ID & "''"
Dim strConnString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd = New SqlCommand(ds, con)
Try
con.Open()
GridView1.EmptyDataText = "No equipment with that Asset ID"
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
But it is not displaying the information Unclosed quotation mark after the character string '1001''.Incorrect syntax near '1001''
If AssetID is defined as numeric at database level the SQL statement should be:
"SELECT * FROM Medical_Equipment WHERE AssetID=" & ID
If it is defined as text then should be:
"SELECT * FROM Medical_Equipment WHERE AssetID='" & ID & "'"
I think you have a typo here:
Try this:
"Select * from Medical_Equipment where AssetID='" & ID & "'"
Im currently building a project that lets users import Excel files via a web interface (built), which saves the file to the server (built), and then imports the data into the SQL Database on the server depending on a few of the user options (not built).
Im not familiar with SQL database tools within VS at all so I have been fumbling around for the better part of two days just trying to get everything set up. Im pretty sure I need to use BulkCopy, but Im not quite sure how to use it and I can't seem to find specific examples that explain it pertaining to my specific application.
So in my App_Data folder I have an .mdf title "Device Database." In that database I have three tables: "Galaxy Nexus", "Hercules" , and "Ruby"
I am trying to import four cells from each imported excel sheet to their respective tables.
I would like to import cell(2,2) to column1 in the table, cell(2,3) to column2, cell(3,2) to column3 and cell(1,1) to column4.
The code I am trying to accomplish this with is:
Dim ExcelContentType As String = "application/vnd.ms-excel"
Dim Excel2010ContentType As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim excelConnectionString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", SavedFile)
Using connection As New OleDbConnection(excelConnectionString)
Dim Command As OleDbCommand = New OleDbCommand("Select * FROM [Sheet1$]", connection)
connection.Open()
Using reader As DbDataReader = Command.ExecuteReader()
Dim sqlConnectionString As String = "Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True"
Using bulkCopy As New SqlBulkCopy(sqlConnectionString)
bulkCopy.DestinationTableName = DropDown1.SelectedItem.ToString
bulkCopy.WriteToServer(reader)
End Using
End Using
End Using
Where I am having trouble is, I do not know how to select certain cells from the excel sheet to import and I do not know how to copy those cells to specific columns in the specified table.
Any and all help is always appreciated.
Thanks,
Zach
Im posting an answer so that if anyone else stumbles upon this, they might be helped as well.
This is what got everything to work for me. (Shout out to kevin)
Protected Sub Button1_Click(sender As Object, e As System.EventArgs)
Dim appPath As String = Request.PhysicalApplicationPath
Dim con As New System.Data.SqlClient.SqlConnection
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
con.Open()
MsgBox("open")
con.Close()
MsgBox("close")
End Sub
This got the connection open after much trying and frustration.
This got the excel values imported to the database:
Using con As New SqlClient.SqlConnection With
{
.ConnectionString =
"Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
}
Using cmd As New SqlClient.SqlCommand With
{
.Connection = con,
.CommandText = "INSERT INTO " & """" & DropDownList1.SelectedItem.ToString & """" & "ColumnName1, ColumnName2)VALUES (#Col1,#Col2)"
}
cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "#Col1"})
cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "#Col2"})
cmd.Parameters(0).Value = "Value obtained from Excel"
cmd.Parameters(1).Value = "Value obtained from Excel"
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery
If Result <> 1 Then
MessageBox.Show("Insert failed.")
Else
MessageBox.Show("Row inserted.")
End If
End Using
End Using
Enjoy guys!
Use Excel Data Reader dll for this. It will read the excel file and give the Dataset as result.
simple code for 'abcConnectionString' as a connection string
and 'pqr_table' as sql table.
'Sheet1' is for the sheet1 of excel file.
important thing is the table format ie rows n columns of excel n database file should b same
her is the vb.net code foe veb application
one FileUpload with name 'FileUpload1'
and one button.
this code is in side the buton method
Dim excelConnectionString As String = String.Empty
Dim uploadPath As String = "~/Uploads/"
Dim filePath As String = Server.MapPath(uploadPath + FileUpload1.PostedFile.FileName)
Dim fileExt As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim strConnection As [String] = ConfigurationManager.ConnectionStrings("abcConnectionString").ConnectionString
If fileExt = ".xls" OrElse fileExt = "XLS" Then
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & filePath & "'" & "; Extended Properties ='Excel 8.0;HDR=Yes'"
ElseIf fileExt = ".xlsx" OrElse fileExt = "XLSX" Then
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=Excel 12.0;Persist Security Info=False"
End If
Dim excelConnection As New OleDbConnection(excelConnectionString)
Dim cmd As New OleDbCommand("Select * from [Sheet1$]", excelConnection)
excelConnection.Open()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader()
Dim sqlBulk As New SqlBulkCopy(strConnection)
sqlBulk.DestinationTableName = "pqr_table"
sqlBulk.WriteToServer(dReader)
MsgBox("Congratulations! Successfully Imported.")
excelConnection.Close()
simple code for 'abcConnectionString' as a connection string and 'pqr_table' as sql table. 'Sheet1' is for the sheet1 of excel file. important thing is the table format ie rows n columns of excel n database file should b same
here is the vb.net code foe veb application one FileUpload with name 'FileUpload1' and one button. this code is in side the buton method
Dim excelConnectionString As String = String.Empty
Dim uploadPath As String = "~/Uploads/"
Dim filePath As String = Server.MapPath(uploadPath + FileUpload1.PostedFile.FileName)
Dim fileExt As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim strConnection As [String] = ConfigurationManager.ConnectionStrings("abcConnectionString").ConnectionString
If fileExt = ".xls" OrElse fileExt = "XLS" Then
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & filePath & "'" & "; Extended Properties ='Excel 8.0;HDR=Yes'"
ElseIf fileExt = ".xlsx" OrElse fileExt = "XLSX" Then
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=Excel 12.0;Persist Security Info=False"
End If
Dim excelConnection As New OleDbConnection(excelConnectionString)
Dim cmd As New OleDbCommand("Select * from [Sheet1$]", excelConnection)
excelConnection.Open()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader()
Dim sqlBulk As New SqlBulkCopy(strConnection)
sqlBulk.DestinationTableName = "pqr_table"
sqlBulk.WriteToServer(dReader)
MsgBox("Congratulations! Successfully Imported.")
excelConnection.Close()
"[..] security info=False;initial catalog=pooja2011"
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "UPDATE a1_ticket SET BANK = '" & Literal20.Text & "' AND PAID = '" & Label1.Text & "'AND BID = '" & Literal21.Text & "' WHERE Ticket_no ='" & Literal3.Text & "'"
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
ERROR : Incorrect syntax near AND
You are not using parametrized queries and thus making your code vulnerable to SQL injection. Here's how to improve it:
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a1_ticket SET BANK = #bank, PAID = #paid, BID = #bid WHERE Ticket_no = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
Well, the AND doesn't have a space after the single quote:
Label1.Text & "'AND BID = '"
should probably be:
Label1.Text & "' AND BID = '"
If this doesn't resolve your issue, can you post your error message?