SQL Server CE query having no effect? - sql

I'm attempting to insert rows into a SQL Server CE database, and it's returning that 1 row is affected, there's no exception, and no syntax error in the query as far as I can see - but it's having no effect, when I look in the table from the Database Explorer.
If I run a query through VS, everything works fine. There's no connection problem as far as I can tell... what am I doing wrong here?
Here's the code, though it probably doesn't make a difference:
Using conn As New SqlCeConnection(My.Settings.DietSafetyCheckerReportsConnectionString)
conn.Open()
Using cmd As SqlCeCommand = conn.CreateCommand()
cmd.CommandText = "INSERT INTO Reports(PatientID, PreparedBy, PreparedFor, WeightInKilos, HeightInMeters, Age, PercentBodyFat, ElbowMeasurementInCentimeters, ReportDate, Gender) " &
"VALUES(#pid, #pby, #pfor, #weight, #height, #age, #bodyfat, #elbow, #rdate, #gender);"
cmd.Parameters.Add("#pid", SqlDbType.NVarChar, 100).Value = Me.PatientID
cmd.Parameters.Add("#pby", SqlDbType.NVarChar, 100).Value = Me.PreparedBy
cmd.Parameters.Add("#pfor", SqlDbType.NVarChar, 100).Value = Me.PreparedFor
cmd.Parameters.Add("#weight", SqlDbType.Float).Value = Me.WeightInKilos
cmd.Parameters.Add("#height", SqlDbType.Float).Value = Me.HeightInMeters
cmd.Parameters.Add("#age", SqlDbType.TinyInt).Value = Me.Age
cmd.Parameters.Add("#bodyfat", SqlDbType.Float, 100).Value = Me.PercentBodyFat
cmd.Parameters.Add("#elbow", SqlDbType.TinyInt, 100).Value = Me.ElbowMeasurementInCentimeters
cmd.Parameters.Add("#rdate", SqlDbType.DateTime).Value = Me.ReportDate
cmd.Parameters.Add("#gender", SqlDbType.TinyInt, 100).Value = Me.Gender
If cmd.ExecuteNonQuery() <> 1 Then Throw New ApplicationException("Failed to insert row into databse.")
End Using
conn.Close()
End Using
(By the way, this also doesn't work:
Using da As New SqlCeDataAdapter("SELECT * FROM Reports", conn)
Dim ds As New DietSafetyCheckerReportsDataSet()
Dim dt As DietSafetyCheckerReportsDataSet.ReportsDataTable
da.Fill(ds)
dt = DirectCast(ds.Tables("Reports"), DietSafetyCheckerReportsDataSet.ReportsDataTable)
Dim dr As DietSafetyCheckerReportsDataSet.ReportsRow = dt.NewReportsRow()
dr.Age = Me.Age
dr.ElbowMeasurementInCentimeters = Me.ElbowMeasurementInCentimeters
dr.Gender = Me.Gender
dr.HeightInMeters = Me.HeightInMeters
dr.PatientID = Me.PatientID
dr.PercentBodyFat = Me.PercentBodyFat
dr.PreparedBy = Me.PreparedBy
dr.PreparedFor = Me.PreparedFor
dr.ReportDate = Me.ReportDate
dr.WeightInKilos = Me.WeightInKilos
dt.Rows.Add(dr)
da.Update(ds)
End Using
)

Look in your bin/debug folder, you probably have more copies of the same database file

My suggestion is that you turned off autocommit mode on server (which is on by default) or on connection settings, so you need to commit your transaction manually. Take a look here for more info.

Related

SQL Error Regarding apostrophe from datagridview using parameter in query

Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0))
end with
The value from the datagrid view contains an apostrophe where I get an error in ('s). Any work around with this?
EDIT:
This is the error:
SqlException was unhandled. Incorrect syntax near 's'.
EDIT 2: i've revised the code to this:
for 1=0 to datagridview.rows.count -1
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0).value)
end with
con.Close()
con.Open()
If Not cmd.ExecuteNonQuery() > 0 Then
con.Close()
Exit For
End If
next
Error is still the same.
As it goes through all the values quickly in one go, I would make the connection once and change the value of the parameter for each iteration, like this:
Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(#sc)"
Using conn As New SqlConnection("your connection string"),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#sc",
.SqlDbType = SqlDbType.NVarChar,
.Size = -1})
conn.Open()
For i = 0 To dgv.Rows.Count - 1
Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
cmd.Parameters("#sc").Value = tname
cmd.ExecuteNonQuery()
Next
End Using
Including the size of the parameter in its declaration helps SQL Server keep things tidy (it only needs one entry in the query cache).
The Using statement makes sure that the connection and command are disposed of properly when they are finished with.
The purpose of checking If Not cmd.ExecuteNonQuery() > 0 was not clear to me, so I didn't put that in.
(I used "dgv" as the name of the DataGridView.)
Try to replace the " ' " by " '' "
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", replace(sc.cells(0), "'", "''")
end with
/**** EDIT ****/
I will consider by the way that your code have a problem with the affectation of the value. You get the value into SC then try to get again the value from cell
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters("#sc").value = sc.replace("'", "''")
end with

VB Get Autonum values

I use the first "Using" statement below to insert a row to a table called "Archives". This table has a primary key that is an autonum in an Access db. The second Using statement I use to retrieve the value for the autonum field, searching by the parameters that I just entered. While this works perfectly well, it just seems ugly. Is there a way to get the autonum field returned to me after the insert? (BTW - I have deleted some code from between these two statements so if it looks a little strange, that may be why.
Using myConn As New OleDbConnection(strConnectionString),
myInsertCommand As New OleDbCommand("INSERT INTO Archives (ArchUserName, ArchUserDomain, ArchDate, ArchRoot, ArchStatus)
VALUES (#strArchUser, #strArchUserDomain, #dteArchDate, #strArchRoot, #strArchStatus);", myConn)
myInsertCommand.Parameters.Add("#strArchUser", OleDbType.VarChar, 100).Value = strArchUser
myInsertCommand.Parameters.Add("#strArchDomain", OleDbType.VarChar, 100).Value = strArchDomain
myInsertCommand.Parameters.Add("#dteArchDate", OleDbType.Date, 20).Value = dteArchDate
myInsertCommand.Parameters.Add("#strArchRoot", OleDbType.VarChar, 255).Value = strArchRoot
myInsertCommand.Parameters.Add("#strArchStatus", OleDbType.VarChar, 100).Value = strArchStatus
myConn.Open()
myInsertCommand.ExecuteNonQuery()
End Using
Dim sql As String = "SELECT ArchID
FROM Archives
WHERE ArchUserName = #ArchUserName
AND ArchUserDomain = #ArchUserDomain
AND ArchDate = #ArchDate
AND ArchRoot = #ArchRoot"
Using myConn As New OleDbConnection(strConnectionString),
command As New OleDbCommand(sql, myConn)
With command.Parameters
.Add("#ArchUserName", OleDbType.VarChar, 50).Value = strArchUser
.Add("#ArchUserDomain", OleDbType.VarChar, 50).Value = strArchDomain
.Add("#ArchDate", OleDbType.Date).Value = dteArchDate
.Add("#ArchRoot", OleDbType.VarChar, 50).Value = strArchRoot
End With
myConn.Open()
strArchID = "Arch" & CStr(command.ExecuteScalar())
strDirectoryName = "Archive" & CStr(command.ExecuteScalar())
ReturnCode = 0
End Using
Use ##Identity on the same connection immediately after the insert.
Private Function InsertArchiveRetrieveID(strArchUser As String, strArchDomain As String, dteArchDate As Date, strArchRoot As String, strArchStatus As String) As Integer
Dim NewID As Integer
Using myConn As New OleDbConnection(strConnectionString),
myInsertCommand As New OleDbCommand("INSERT INTO Archives (ArchUserName, ArchUserDomain, ArchDate, ArchRoot, ArchStatus)
VALUES (#strArchUser, #strArchUserDomain, #dteArchDate, #strArchRoot, #strArchStatus);", myConn)
With myInsertCommand.Parameters
.Add("#strArchUser", OleDbType.VarChar, 100).Value = strArchUser
.Add("#strArchDomain", OleDbType.VarChar, 100).Value = strArchDomain
.Add("#dteArchDate", OleDbType.Date, 20).Value = dteArchDate
.Add("#strArchRoot", OleDbType.VarChar, 255).Value = strArchRoot
.Add("#strArchStatus", OleDbType.VarChar, 100).Value = strArchStatus
End With
myConn.Open()
myInsertCommand.ExecuteNonQuery()
Using RetrieveNewIDCommand As New OleDbCommand("Select ##Identity From Archives,", myConn)
NewID = CInt(RetrieveNewIDCommand.ExecuteScalar)
End Using
End Using
Return NewID
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim NewID = InsertArchiveRetrieveID(txtUser.Text, txtDomain.Text, DateTimePicker1.Value, txtRoot.Text, txtStatus.Text)
Dim strArchID = "Arch" & CStr(NewID)
Dim strDirectoryName = "Archive" & CStr(NewID)
End Sub

"SQL0404: request value for TYPE is too long." error when using parameters

I have a query error with this parameter command. It seems that .NET in the parameter adds extra characters like `vbCrlf. If I try without parameter the update works.
Code:
Dim con As OleDbConnection
Dim txt_tip As String
txt_tip = DataGridView1.Rows(i).Cells(0).Value.ToString(0)
conn.ConnectionString = "Provider=IBMDA400;Data Source=172.xx.xx.xx;User Id=user;Password=pwd;"
con = New OleDbConnection(conn.ConnectionString)
con.Open()
Using updCommand As New OleDbCommand("UPDATE $Customers SET TYPE=#type, Name='Rob', Surname='Red', Desc='Test10' WHERE ID=100", con)
updCommand.Parameters.Add("#type", OleDbType.VarChar, 1).Value = txt_tip
updCommand.ExecuteNonQuery()
End Using
If I try it without the parameters the query works fine:
"UPDATE $Customers SET TYPE='1', Name='Rob', Surname='Red', Desc='Test10' WHERE ID=100"
The server is IBM AS400.
OP posted answer in comments
Instead of of specifying a name for the parameter use a ? as a placeholder:
Using updCommand As New OleDbCommand("UPDATE $Customers SET TYPE=?, Name='Rob', Surname='Red', Desc='Test10' WHERE ID=100", con)
updCommand.Parameters.Add("?", OleDbType.Char).Value = txt_tip
...
End Using
If you want to add more just ensure the order is correct:
Using updCommand As New OleDbCommand("UPDATE $Customers SET TYPE=?, Name=?, Surname=?, Desc='Test10' WHERE ID=100", con)
updCommand.Parameters.Add("?", OleDbType.Char).Value = txt_tip
updCommand.Parameters.Add("?", OleDbType.VarChar).Value = "Rob"
updCommand.Parameters.Add("?", OleDbType.VarChar).Value = "Red"
...
End Using

No value given for one or more required parameters. during paramatized search

I am trying a paramatized search to prevent sql injection. However the error
"No value given for one or more required parameters". comes
Dim sql As String
Call connect()
con.Open()
sql = "Select * from Records where Customer_ID=#CustomerID"
cmd.Parameters.AddWithValue("#CustomerID", Txt_Customer_ID.Text)
cmd = New OleDbCommand(sql, con)
dr = cmd.ExecuteReader
While dr.Read
Txt_Customer_ID.Text = dr(0)
Txt_Customer_Name.Text = dr(1)
Txt_Customer_Contact.Text = dr(2)
Txt_Delivery_Method.Text = dr(3)
Txt_Reference.Text = dr(4)
End While
con.Close()
The Customer_ID field in the database is a text type and I need to know how to finish this search without running into the error
Got the answer! Thank you to everyone who tried
cmd.Parameters.AddWithValue("#CustomerID", Txt_Customer_ID.Text)
line must be below
cmd = New OleDbCommand(sql, con)
Here is the code that works
Dim sql As String
Call connect()
con.Open()
sql = "Select * from Records where Customer_ID=#CustomerID"
cmd = New OleDbCommand("Select * from Records where Customer_ID=#CustomerID", con)
cmd.Parameters.AddWithValue("#CustomerID", Txt_Customer_ID.Text)
dr = cmd.ExecuteReader
While dr.Read
Txt_Customer_ID.Text = dr(0)
Txt_Customer_Name.Text = dr(1)
Txt_Customer_Contact.Text = dr(2)
Txt_Delivery_Method.Text = dr(3)
Txt_Reference.Text = dr(4)
End While
con.Close()
Change the order like this
cmd = New OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#CustomerID", Txt_Customer_ID.Text)

Update multiple rows in access database using oledb parameters

I am trying to update multiple rows in a access database using parameters. I already have to code to insert to a database, but I need same type of code to update the database.
My update string looks like this Update tblitem set instock='value' where itemcode='value2'
Here is my code to insert:
strSQL = "insert into tbltrans2 (transid,itemcode,itemname,qty,price,[total],btw) values ( ?,?,?,?,?,?,?)"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtTransId.Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cmd.Parameters.Add("?", OleDbType.Integer)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
cmd.ExecuteNonQuery()
Next ls
End Using
You should, at the most basic level, be able to modify your sql string to indicate parameter placeholders (?) as you did in your Insert query, eg
Update tblitem set instock=? where itemcode=?
The concept beyond that, eg creating/setting the parameters, is essentially the same. Hope I'm understanding your problem properly. Good luck.