Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Dim reserveTime As String
Dim Timer As String = ddlTime.SelectedValue
Dim dat As String
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Beauty shop\Beauty shop\Beauty.accdb'")
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
Dim reserveDate As String = Calendar1.SelectedDate
Dim bookingTime As String = "SELECT Booking_Date,Booking_Time FROM CustomerBooking where Booking_Date='" & reserveDate & "'"
Dim sqlcommand2 As New OleDbCommand(bookingTime, conn)
Dim dr2 As OleDbDataReader
dr2 = sqlcommand2.ExecuteReader
If dr2.HasRows Then
dr2.Read()
Dim count As Integer = dr2.FieldCount
While dr2.Read()
For i As Integer = 0 To count - 1
dat = dr2.Item("Booking_Date")
reserveTime = dr2.Item("Booking_Time")
Next
End While
dr2.Close()
If Timer = reserveTime And dat = reserveDate Then
ShowTimeLbl.Text = "This time have been reserve"
Else
Dim sqlString As String
sqlString = "Insert INTO CustomerBooking(Customer_Name, Package_Name, Price, Booking_Date, Booking_Time, Card_Bank, Cardholder_Name, Card_Number,Expired_Month,Expired_Date) VALUES ('" & User_Name & "','" & Package_Name & "','" & Price_Package & "','" & Calendar_Book & "','" & Time_Book & "','" & Card_Name & "','" & Card_Holder & "','" & CreditCard_Number & "','" & Month_Card & "','" & Year_Card & "')"
Dim sqlcommand As New OleDbCommand(sqlString, conn)
sqlcommand.ExecuteNonQuery()
conn.Close()
Response.Redirect("ConfirmBook.aspx?Name=" + Master.NameMaster + "&UserName=" + User_Name + "&PackageName=" + Package_Name + "&PackagePrice=" + Price_Package + "&Calender=" + Calendar_Book + "&TimeBook=" + Time_Book + "&CardName=" + Card_Name + "&CardHolder=" + Card_Holder + "&CreditCardNumber=" + CreditCard_Number + "&MonthCard=" + Month_Card + "&YearCard=" + Year_Card)
End If
End If
when i choose time all date cannot run, what is my problem, i want to compare the date and the time, if time has been booking it will show full,but just can read first date , why cannot run second date?the date is same
You have kept an extra dr.Read before while loop.
If dr2.HasRows Then
***dr2.Read()***
Dim count As Integer = dr2.FieldCount
While dr2.Read()
For i As Integer = 0 To count - 1
Remove the extra read() statement and get the field count inside while loop. It should work fine.
If dr2.HasRows Then
While dr2.Read()
Dim count As Integer = dr2.FieldCount
For i As Integer = 0 To count - 1
UPDATE-
I am putting a pseudo code just to give you an idea. There is a lot of room for improvement. But since it is not a code review, I will keep quite on that matter.
query = "SELECT Booking_Date,Booking_Time FROM CustomerBooking where Booking_Date= <inputDate> & and Booking_Time=<inputTime>"
dr2 = get datareader using <query>
If dr2.HasRows Then
'It means there are records in DB with input date and Time so show error
Else
'code to insert'
End If
Related
I have a problem saving an image from ASP.NET webforms showing data in SQL Server database table
0x000
My code to save the image in ASP.NET page is:
Dim Stream As IO.Stream
Dim FileLen As Integer
Dim FileOK As Boolean = False
Dim dt As New Data.DataTable
Dim SqlStr As String = String.Empty
If FileUpload1.HasFile Then
Dim FileExtension As String, FileSize As Integer, Height As Integer, Width As Integer
FileSize = FileUpload1.FileBytes.Count() / 1024
FileExtension = IO.Path.GetExtension(FileUpload1.FileName).ToLower()
Dim Img As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
Height = Img.Height
Width = Img.Width
If FileSize <= 100 Then
If Width <= 700 AndAlso Height <= 500 Then
If FileExtension = ".jpg" Or FileExtension = ".png" Or FileExtension = ".jpeg" Then
FileOK = True
Else
FileOK = False
End If
If FileOK Then
FileLen = FileUpload1.PostedFile.ContentLength
Dim fltp As String = FileUpload1.PostedFile.ContentType
Dim MyData(FileLen) As Byte
Stream = FileUpload1.FileContent
Stream.Read(MyData, 0, FileLen)
Dim decfileparameter As New Data.SqlClient.SqlParameter("#ImgBinary", Data.SqlDbType.Binary)
decfileparameter.Value = MyData
Dim Action As Integer = 1
SqlStr = "SaveUpdateSubServicesToMaster '" & Action & "','" & ddServiceTypeName.SelectedValue & "','" & TxtSubServiceName.Text & "','" & TxtPriceB4Txt.Text & "','" & TxtBasicPrice.Text & "','" & TxtAfterPrice.Text & "','" & TxtAboutSrvc.Text & "','" & TxtTrunTime.Text & "','" & TxtFinalBill.Text & "','" & TxtDuration.Text & "','" & DDIsSerAvl.SelectedValue & "','0',#ImgBinary"
Dim sqlConnString As String = Web.Configuration.WebConfigurationManager.ConnectionStrings("NewSHCService").ConnectionString
Dim con As New Data.SqlClient.SqlConnection(sqlConnString)
Dim sqlcmd As New Data.SqlClient.SqlCommand(SqlStr, con)
sqlcmd.Parameters.Add(decfileparameter)
con.Open()
Using sdr As Data.SqlClient.SqlDataReader = sqlcmd.ExecuteReader()
dt.Load(sdr)
End Using
con.Close()
as when storing data trough stored procedure taking varbinary(max) to insert data into table.
But it is not saving the image.
When I directly store image through
UPDATE dbo.ServiceSubTypeMaster
SET ServiceSubTypeImage = (SELECT BulkColumn
FROM OPENROWSET(BULK 'C:\Users\TanDev\Desktop\Imgs_New_Shc_Services\SameSize\134.jpg', SINGLE_BLOB) AS X)
WHERE ServiceSubTypeID = 137
it's showing image properly.
I have a web form project to update columns in an Microsoft SQL 2012 database table. When I "hard code" the connection info for my SqlConnection everything works fine. However if I try going the ConfigurationManager.ConnectionStrings route I get a keyword 'id' not supported. I have included the Imports.System.Configuration code into my project. Below is the Sub where I am running into the issue
Protected Sub BtnSubmit_Click(sender As Object, e As EventArgs) Handles BtnSubmit.Click
Dim myConn As SqlConnection
Dim cmd As SqlCommand
Dim sqlstring, RqType, RqLast, RqFirst, RqOrg, RqEmail, RqNeedDate, SubFirst, SubLast, RqDetails, RqGenDate, RqOperator As String
RqType = cbxRequestType.SelectedValue
RqLast = txtReqLastName.Text
RqFirst = txtReqFirstname.Text
RqOrg = txtOrganization.Text
RqEmail = txtEmail.Text
RqNeedDate = txtReqDate.Text
SubFirst = txtSubFirst.Text
SubLast = txtSubLast.Text
RqDetails = txtReqDetails.Text
RqGenDate = txtGenDate.Text
RqOperator = txtOperator.Text
If Agree.Checked = False Then
MsgBox("You must agree to the terms before proceeding")
Else
myConn = New SqlConnection(ConfigurationManager.ConnectionStrings("PRRWeb").ConnectionString)
myConn.Open()
sqlstring = "INSERT INTO Requests (LastName, FirstName, Organization, DateRequested, DateNeeded, OperatorID, SubjectLastName, SubjectFirstName, Notes, TypeID, Email) VALUES ('" + RqLast + "','" + RqFirst + "', '" + RqOrg + "','" + RqGenDate + "', '" + RqNeedDate + "','" + RqOperator + "','" + SubLast + "','" + SubFirst + "','" + RqDetails + "','" + RqType + "','" + RqEmail + "')"
cmd = New SqlCommand(sqlstring, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
MsgBox("Your request has been submitted.", MsgBoxStyle.Information)
Response.Redirect(Request.RawUrl)
End If
Resolved the issue by adding a connectionstring to my web.config like so
<connectionStrings >
<add
name="PRRWeb"
connectionString="Server=server;Database=DB;Timeout=200;User ID=user; Password=Password; Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
And then added this to my vb code
myConn = New SqlConnection(ConfigurationManager.ConnectionStrings ("PRRWeb").ConnectionString)
I'm really new to ASP.net and I am currently trying to create a registration page on a site. I was successful in adding a user to the database but I decided to add another feature into the code to check what userID's were available. For example, if a user deleted their account their userID would become available for use again. I'm trying to find the min value and the max value and add or subtract 1 depending on whether it is min or max. I can run the code I have written for this with no errors but the user is not added to the database. Can anyone help me figure out what I'm missing from my code to do this?
EDIT >>>>>
Code adds a user to database but it adds the new user at -1 instead. I don't seem to be able to see where the issue is.
If (aDataReader2.Read() = False) Then
aConnection1 = New OleDbConnection(aConnectionString)
aConnection1.Open()
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection1)
aCommand.ExecuteNonQuery()
aConnection1.Close()
ElseIf (min = 1) Then
aConnection2 = New OleDbConnection(aConnectionString)
aConnection2.Open()
aCommand = New OleDbCommand(aQuery3, aConnection2)
aDataReader2 = aCommand.ExecuteReader()
userID = max + 1
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection2)
aCommand.ExecuteNonQuery()
aConnection2.Close()
Else
aConnection3 = New OleDbConnection(aConnectionString)
aConnection3.Open()
aCommand = New OleDbCommand(aQuery2, aConnection3)
aDataReader2 = aCommand.ExecuteReader
userID = min - 1
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection3)
aCommand.ExecuteNonQuery()
aConnection3.Close()
lblResults.Text = "User Account successfully created"
btnCreateUser.Enabled = False
End If
Here's the code I used to get the max and min values from the database. I'm getting a value of 0 for both of them - when min should be 1 and max should be 5
Dim minID As Integer
Dim maxID As Integer
aQuery2 = "Select Min(UserID) AS '" & [minID] & "' From UserDetails"
aQuery3 = "Select Max(UserID) AS ' " & [maxID] & "' From UserDetails"
It's hard to say what
t the problem is exactly, since we see only a part of it. Where do min and max come from?
I cannot give you a solution, however, I suggest you to structure your code better. You have a lot (!) of redundant code. This makes the code difficult to read, to understand, to change and to test.
Put the user data into a class. This makes it easier to handle than a lot of individual variables.
Public Class User
Public Property ID As Integer
Public Property FirstName As String
Public Property LastName As String
Public Property EMail As String
Public Property Username As String
Public Property Password As String
End Class
Extract redundant code into subroutines
Private Sub CreateUser(ByVal u As User)
Const InsertQuery As String = _
"INSERT INTO UserDetails VALUES ({0},'{1}','{2}','{3}','{4}','{5}')"
Dim query As String = String.Format(InsertQuery, u.ID, u.FirstName, u.LastName, _
u.Email, u.Username, u.Password)
Using conn As New OleDbConnection(aConnectionString)
conn.Open()
Dim cmd As New OleDbCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Sub
The code then becomes something like this
If Not aDataReader2.Read() Then
CreateUser(user)
ElseIf min = 1 Then
...
user.userID = max + 1
CreateUser(user)
Else
...
user.userID = min - 1
CreateUser(user)
lblResults.Text = "User Account successfully created"
btnCreateUser.Enabled = False
End If
This looks much nicer now.
(My code is not tested, it's just to give you an idea.)
UPDATE
You cannot read the min and max values like this. Try something like this
Dim min, max As Integer
Using conn As New OleDbConnection(aConnectionString)
Dim cmd As OleDbCommand = _
New OleDbCommand("SELECT MIN(UserID), MAX(UserID) FROM UserDetails", conn)
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
reader.Read()
If reader.IsDBNull(0) Then
' The table is empty
min = 1
max = 1
Else
min = reader.GetInt32(0)
max = reader.GetInt32(1)
End If
End Using
End Using
I am having problems uploading CSV files to my SQL Database. I am trying to achieve this through the File Upload technique on an intranet site. The intranet site is for me and another user to have the ability to file upload these CSVs (in case one of us is out).
I've used the following;
Dim errorList As String = String.Empty
Dim returnValue As Integer = 0
Dim SQLCon As New SqlClient.SqlConnection
Dim SQLCmd As New SqlClient.SqlCommand
Dim ErrString As String
Dim countRecs As Integer = 0
Dim batchid As Integer = GetNextBatchNumber("PartsImport")
Using tf As New TextFieldParser(fileandpath)
tf.TextFieldType = FileIO.FieldType.Delimited
tf.SetDelimiters(",")
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (ID,PartName,PartID,Price,ShipAddress) " _
+ " values ('" + row(0) + "','" + row(1) + "','" _
+ row(2) + "','" + row(3) + "','" + row(4) + "')"
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close()
SQLCon.Dispose()
SQLCmd.Dispose()
When I click the form button to upload, it gives me a success message but when I look in the actual table, it is still blank.
Any ideas? Appreciate it
Thanks
Dave
private void UploaddataFromCsv()
{
SqlConnection con = new SqlConnection(#"Data Source=local\SQLEXPRESS;Initial Catalog=databaseName;Persist Security Info=True;User ID=sa");
string filepath = "C:\\params.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while ( !sr.EndOfStream )
{
value = sr.ReadLine().Split(',');
if(value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "[Base].[PartsImport]";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
Try catching a SqlException and seeing if there is a formatting issue with your request. If you have an identity column on the ID, you shouldn't set it explicitly from your CSV as that may cause a potential duplicate to be submitted to your database. Also, I suspect that you have some type mismatches in your types since you are putting quotes around what appear to be number columns. I would recommend you consider replacing the string concatenation in your query to using parameters to avoid issues with improper quote escaping (ie. what would happen if you have a PartName of "O'Reily's auto parts"?) Something like this may work. Note, I've been in the LINQ world for so long, I may have some syntax errors here.
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text 'Setup Command Type
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (PartName,PartID,Price,ShipAddress) " _
+ " values (#PartName, #PartID, #Price, #ShipAddress)'"
Dim partNameParam = New SqlParameter("#PartName", SqlDbType.VarChar)
Dim partIdParam = New SqlParameter("#PartID", SqlDbType.Int)
Dim partPriceParam = New SqlParameter("#Price", SqlDbType.Money)
Dim partAddressParam = New SqlParameter("#ShipAddress", SqlDbType.VarChar)
SQLCmd.Parameters.AddRange( {partNameParam, partIdPAram, partPriceParam, partAddressParam})
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString()
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
partNameParam.Value = row[1]
partIdParam.Value = row[2]
partPriceParam.Value = row[3]
partAddressParam.Value = row[4]
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close() 'TODO: Change this to a Using clause
SQLCon.Dispose()
SQLCmd.Dispose() 'TODO: Change this to a Using clause
With all that being said, if you have any significant number of items to insert, the bulk copy example is a better answer.
I have this code and its coming up with an INSERT INTO statement error...
Its probably something but I have been at it for a while... please help.
'Add items to db'
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')"
myCommand2.Connection = con2
con2.Open()
myCommand2.ExecuteReader()
con2.Close()
test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" "
Next
End Function
I think you are getting an error by not enclosing the Date inside Pound signs. You have to do this in Jet (Access) when using variables not parameters.
VALUES('#" & DateTime.Now.Date & "#',...
I also took the liberty of refactoring this code for you since you are creating a new connection for each record which is bad news. Use a Try Catch Finally block and move all that stuff outside the For Loop (please see below)
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" <-- etc
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.Connection = con2
con2.Open()
Try
For intCounter = 0 To obDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _
& "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _
& "','" & Int32.Parse(objDR("quantity")) & "')"
myCommand2.ExecuteReader()
Next
Catch ex As Exception
'handle errors here
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
Remember to mark as answered if this helps.
I've sorted it out by removing the single quotes. Thanks everybody to contributed to this.