I've been getting the following error when trying to write data from my HMI to a MSSQL db using ADODB.recordset with the AddNew/Update Methods. I'm using SQL Server Native Client 11.0 for the connection and Microsoft ActiveX Data Objects 6.0 Library.
Generic VBA Error -2147467259[Microsoft][SQL Server Native Client 11.0][SQL Server]FNGCO,ABCDEFGHI,1000003,2017-04-14,17:00:36:187,FOAML1,A1,,1
If it works this code should write each value to each column in the MSSQL database. I've got very similar code working in another part of the application, but I can't seem to get this working.
What I Have Tried So Far:
Checked against code running in another HMI, everything between the two appears to be identical.
Tried the same connection string with another ADODB.recordset and added data to the db with AddNew/Update.
Checked the database table to make sure all of the data I'm trying to enter fits the column (its not null, max characters not exceeded, etc...)
Here is my code:
On debug, the code halts at sqlrs1.Update.
Option Explicit
Const strSQLNCLI11_1 = "Driver={SQL Server Native Client 11.0};Server=TESTDEMO\SQLEXPRESS;Database=RABPI;Uid=sa;Pwd=testdemo;QueryTimeout=0"'
Private Sub Button1_Released()
On Error GoTo ErrHandler
Dim sqlcn2 As ADODB.Connection
Dim sqlrs1 As ADODB.Recordset
Set sqlcn2 = New ADODB.Connection
Set sqlrs1 = New ADODB.Recordset
sqlcn2.Open strSQLNCLI11_1
sqlrs1.Open "Select * from AT_BW_PRDN ;", _
sqlcn2, adOpenDynamic, adLockPessimistic
sqlrs1.AddNew
sqlrs1("AT_BW_BUS_UNIT") = "FNGCO"
sqlrs1("AT_BW_PID") = "ABCDEFGHI"
sqlrs1("AT_BW_PRDN_AREA") = "FOAML1"
sqlrs1("AT_BW_SHIFT") = "A1"
sqlrs1("AT_BW_ITEM_ID") = "1000007"
sqlrs1("AT_BW_REL") = 0
sqlrs1.Update
Exit Sub
ErrHandler:
LogDiagnosticsMessage "Generic VBA Error" & Err.Number & " " & Err.Description, ftDiagSeverityError, ftDiagAudienceOperator
Set sqlcn2 = Nothing
Set sqlrs1 = Nothing
Exit Sub
End Sub
UPDATE:
I made a test database and re-created the tables I'm trying to write to without any constraints or triggers and the code functioned properly.
Related
I successful Adding image in SQL database using Stream class in that code
Public CN As New ADODB.Connection
Public Emp As New ADODB.Recordset
Public ST As New ADODB.Stream
Emp.Open("Employees", CN, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)
Emp.AddNew()
ST.Open()
ST.Type = ADODB.StreamTypeEnum.adTypeBinary
ST.LoadFromFile(OpenFileDialog1.FileName)
Emp(19).Value = ST.Read
Emp.Update()
ST.Close()
Emp.Close()
this operation is successful but when I retrieve the database using this Code:
Emp.Open("Select * From Employees Where UserName = '" + TXTSearch.Text + "'", CN)
ST.Open()
ST.Type = ADODB.StreamTypeEnum.adTypeBinary
ST.Write(Emp.Fields(19).Value)
ST.SaveToFile("\temp", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
PICEmployee.Image = Image.FromFile("\temp")
ST.Close()
Emp.Close()
I have a button to show the database grid and it confirm the picture is loaded
but when I tried to fetch the data it stopped in that line
ST.SaveToFile("\temp", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
says Failed to Write I changed the Path got same error, I open the VB as Administrator got same error.
Tip: I didn't send All my Codes in case if something missing but everything about Stream is here
I like to have simple solution I'm still beginner and Need all Help you can give to me, Thanks
[EDIT - This issue is resolved. The problem had to do with uninitialized out parameters on the stored procedure.]
Why would I need to turn connection pooling off to get this to work correctly???
[EDIT - connection pooling released a shared connection memory area on the AS400]
In my MVC web app I call a DB2 Stored Procedure (SP).
This SP has multiple in and out parameters similar to this pseudo code:
CreatePO(#REQNO[in], #PO[out], #Approver[out], #ErrorMsg[out])
My app writes data to tables used by this SP during its processing so when all the data is in place I call the SP and it tries to create a PO.
If the PO creation fails there will be an error message in the #ErrorMsg out parameter. In these cases the #PO and #Approver parameters should be blank.
Here's what happens in sequence:
1) I try to create my first PO but there is a problem...
CreatePO(100, blank, blank, blank)
which results in...
CreatePO(100, blank, blank, 'unable to determine approver')
2) I successfully create the 2nd PO...
CreatePO(101, blank, blank, blank)
CreatePO(101, 'P1234', 'JJONES', blank)
3) I try to re-create a PO for #REQNO 100
CreatePO(100, blank, blank, blank)
CreatePO(100, 'P1234', 'JJONES', 'unable to determine approver')
Step 3 has conflicting out parameters. The app pool is returning the PO and Approver from Step 2 along with the appropriate an error message.
If I recycle my IIS app pool then the results are back to what happened in Step #1.
I am able to get expected results I add "pooling=false" to the connection string. But why would output parameters be affected in this manner by connection pooling? This seems more like a bug than some sort of desirable caching method.
If I don't paste my code someone will get bent out of shape so here it is...
(Look at the end of the top two lines)
'Dim cs As String = "DataSource=mydb;UserID=myuser;Password=mypassword;Naming=System;ConnectionTimeout=180; DefaultIsolationLevel=ReadUncommitted;AllowUnsupportedChar=True;CharBitDataAsString=True; TransactionCompletionTimeout=0;pooling=false"
Dim cs As String = "DataSource=mydb;UserID=myuser;Password=mypassword;Naming=System;ConnectionTimeout=180; DefaultIsolationLevel=ReadUncommitted;AllowUnsupportedChar=True;CharBitDataAsString=True; TransactionCompletionTimeout=0;"
Using conn As New iDB2Connection(cs)
conn.Open()
Dim cmd As iDB2Command = New iDB2Command()
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "BF6360CL"
' Input parameters
cmd.Parameters.Add(New iDB2Parameter With {.ParameterName = "#REQNO", .DbType = SqlDbType.Char, .Size = 7, .Value = model.RO})
' Output parameters
Dim opo = New iDB2Parameter With {.ParameterName = "#POORDER", .DbType = SqlDbType.Char, .Size = 7, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(opo)
Dim oApprover = New iDB2Parameter With {.ParameterName = "#APPROVER", .DbType = SqlDbType.Char, .Size = 10, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(oApprover)
Dim oStatus = New iDB2Parameter With {.ParameterName = "#STATUS", .DbType = SqlDbType.Char, .Size = 3, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(oStatus)
Dim oErr = New iDB2Parameter With {.ParameterName = "#ERROR", .DbType = SqlDbType.Char, .Size = 1, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(oErr)
' return value
Dim oRetval = New iDB2Parameter With {.ParameterName = "#RETURN_VALUE", .DbType = SqlDbType.Char, .Size = 10, .Direction = ParameterDirection.ReturnValue}
cmd.Parameters.Add(oRetval)
cmd.ExecuteNonQuery()
model.PO = opo.Value
model.Approver = oApprover.Value
model.Status = oStatus.Value
model.Err = oErr.Value
End Using
return model
So the big question is this:
Why on earth would connection pooling be responsible for out parameter values???
Could this be a bug in the IBM iSeries iDB2Connection implementation?
The IIS application pool is caching stored procedure output parameters by name and returning a cached value when nulls are detected. This happens with ODBC or iSeries connections. When I recycled the application pool this cached value went away. I added to the connection string “pooling=false;” and these cached values would no longer appear.
My boss asked me to try calling the stored procedure using iSeries Navigator just to see what the out parameters contain. Boy was I surprised.
It turned out that the Stored Procedure (SP) was at fault after all. I sat with the AS400 RPG developer this morning and watched them debug the SP. The problem had to do with uninitialized memory.
Here's the definition of the SP:
BF6360CL(#REQNO, #USER, #ENVIRONMENT, #PO[out], #Approver[out], #Status[out], #Error[out])
I then reset my connection to the AS400 in iSeries Navigator and the output parameters reset back to
4 = S2.RETU
5 = RN_VAR0000
etc...
The AS400 developer is making changes now to initialize the variables. When they're done I expect to be able to change my program back to use connection pooling.
When I reset the IIS App Pool it reset my connection to the database. This seemed to release allocated memory on the AS400.
If anyone has more specifics about Connections and AS400 output parameter memory please share.
I am new to C# and QBFC13 code and I'm trying to add a bill from code I found on the intuit developer site under the BillAdd section.
The BillAddRq.ExternalGUID.SetValue(Guid.NewGuid().ToString()); is throwing a error:
Invalid GUID format. Must use zero for Custom Fields, or a GUID generated with GuidGen.exe for private data extensions.
I’ve tried:
String guid = System.Guid.NewGuid().ToString("B");
// MessageBox to see that it creates the number
MessageBox.Show("guid", guid);
BillAddRq.ExternalGUID.SetValue(guid);
BillAddRq.ExternalGUID.SetValue(Guid.NewGuid().ToString("B"));
And
String guid = System.Guid.NewGuid().ToString("0");
And those throw:
QB Test 8-14-2014.vshost.exe - No Disk "There is no disk in the drive. Please insert a disk into drive F."
How can I resolve these errors?
Using your first string attempt is the correct format for the GUID. I tested using GUID.NewGuid().ToString("B") and was able to get a GUID that works when adding a bill.
Because you're getting an error about there being no disk in the drive, it sounds like something else is causing the error. I would step through the code and find the exact place that causes the error as it probably has nothing to do with the GUID.
Here's a simple example that I did using a sample file in QuickBooks:
QBSessionManager SessionManager = new QBSessionManager();
SessionManager.OpenConnection2("GUIDTest","GUIDTest", ENConnectionType.ctLocalQBD);
SessionManager.BeginSession("", ENOpenMode.omDontCare);
IMsgSetRequest MsgRequest = sessionManager.CreateMsgSetRequest("US", 13, 0);
MsgRequest.Attributes.OnError = ENRqOnError.roeContinue;
IBillAdd add = MsgRequest.AppendBillAddRq();
add.ExternalGUID.SetValue(System.Guid.NewGuid().ToString("B"));
add.VendorRef.FullName.SetValue("A Cheung Limited");
add.TxnDate.SetValue(DateTime.Today);
IExpenseLineAdd line = add.ExpenseLineAddList.Append();
line.AccountRef.FullName.SetValue("Travel & Lodging");
line.Amount.SetValue(100.00);
IResponse response = sessionManager.DoRequests(MsgRequest).ResponseList.GetAt(0);
MessageBox.Show(response.StatusMessage);
Private Sub OK_Click(sender As System.Object, e As System.EventArgs) Handles OK.Click
If TextBox1.Text = "1234" Then
' This is the connection. You have to have this exact string, except "E:\Documents\notekeeper.mdb" will be the path to your thing instead
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=N:\Visual Studio 2010\Projects\Maths System Aid\Maths System Aid\Database7.mdb;User=;Password=;")
Try
conn.Open()
Catch ex As Exception
MsgBox("Cannot open database")
End Try
' The SQL statement / command
Dim cmd = New OleDbCommand("Insert INTO Student ([First Name], [Surname], [Username], [Password]) VALUES "("" & TextBox5.Text & "," & TextBox4.Text & "," & TextBox3.Text & "," & TextBox2.Text & "" & ")"), conn)
cmd.ExecuteNonQuery() ' Use ExecuteReader() to execute SELECT statements, but ExecuteNonQuery() for others
' Basically, the reader is like an array of all of the records that have been returned by the database
Me.Close()
StudentLogin.Show()
Else
MsgBox("Enter The Correct Confirmation code")
End If
End Sub
my problem is that it will not find my database file. I have followed the path and it is correct. Any ideas of what is the problem?
I haven't done this in quite some time but at the top of your form you should be running some imports firstly
imports system.data
Then you should define rather like this:
dim conn as new oledb.oledbconnection
Another issue I noticed in your code is that you're using the Jet provider which if memory serves correctly only works with the new databases using the .accdb extension. Try to change it to an accdb in access.. I'll go over it quick and see what I can conjure up. Hopefully that helps at least. The alternative provider if you run into issues :
("Provider=Microsoft.ACE.OLEDB.12.0.......
Is this path a local disk or a network disk? is it on another computer or a mapped network drive?
The way I connect is
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:\data\database.mdb;Jet OLEDB:Database Password=******;"
con.ConnectionString = dbProvider & dbSource
con.open()
con.close()
This should work perfect but use your path and password if you have one
Recently, a program that creates an Access db (a requirement of our downstream partner), adds a table with all memo columns, and then inserts a bunch of records stopped working. Oddly, there were no changes in the environment that I could see and nothing in any diffs that could have affected it. Furthermore, this repros on any machine I've tried, whether it has Office or not and if it has Office, whether it's 32- or 64-bit.
The problem is that when you open the db after the program runs, the destination table is empty and instead there's a MSysCompactError table with a bunch of rows.
Here's the distilled code:
var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=corrupt.mdb;Jet OLEDB:Engine Type=5";
// create the db and make a table
var cat = new ADOX.Catalog();
try
{
cat.Create(connectionString);
var tbl = new ADOX.Table();
try
{
tbl.Name = "tbl";
tbl.Columns.Append("a", ADOX.DataTypeEnum.adLongVarWChar);
cat.Tables.Append(tbl);
}
finally
{
Marshal.ReleaseComObject(tbl);
}
}
finally
{
cat.ActiveConnection.Close();
Marshal.ReleaseComObject(cat);
}
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
// insert a value
using (var cmd = new OleDbCommand("INSERT INTO [tbl] VALUES ( 'x' )", connection))
cmd.ExecuteNonQuery();
}
Here are a couple of workarounds I've stumbled into:
If you insert a breakpoint between creating the table and inserting the value (line 28 above), and you open the mdb with Access and close it again, then when the app continues it will not corrupt the database.
Changing the engine type from 5 to 4 (line 1) will create an uncorrupted mdb. You end up with an obsolete mdb version but the table has values and there's no MSysCompactError. Note that I've tried creating a database this way and then upgrading it to 5 programmatically at the end with no luck. I end up with a corrupt db in the newest version.
If you change from memo to text fields by changing the adLongVarWChar on line 13 to adVarWChar, then the database isn't corrupt. You end up with text fields in the db instead of memo, though.
A final note: in my travels, I've seen that MSysCompactError is related to compacting the database, but I'm not doing anything explicit to make the db compact.
Any ideas?
As I replied to HasUp:
According MS support, creation of Jet databases programmatically is deprecated. I ended up checking in an empty model database and then copying it whenever I needed a new one. See http://support.microsoft.com/kb/318559 for more info.