C# ADO.Net to db2 iseries - connection not valid - c#

I'm having problems connecting to a DB2 iSeries database from a C# ADO.Net program.
I can connect from the Windows box to the DB2/iSeries using the ClientAccess "Data Transfer From iSeries" tool, with these settings:
IBM i name: 192.168.0.1
User: VCT130
Passwd: pass
File name: CHGDG#VL/AREA(AREA)
and it retrieves 23 records.
I'm trying to access the same data from a simple C# program summarised below:
using IBM.Data.DB2.iSeries;
string conStr= "DataSource=192.168.0.1;UserID=VCT130;Password=pass;Naming=System;LibraryList=QIWS,CHGDG#VL,CHNNL#VL,CHVAT#VL;DefaultCollection=QIWS;" ;
string sql= "SELECT * from CHGDG#VL/Area;" ; // ALSO TRIED ...from CHGDG#VL/Area(AREA);
iDB2Connection conn = new iDB2Connection(conStr);
iDB2Command cmd = new iDB2Command(sql, conn);
iDB2DataReader rdr = cmd.ExecuteReader();
The conn and cmd objects get created OK, but the ExecuteReader() call fails with:
Unhandled Exception: System.InvalidOperationException: The operation cannot complete because the connection is not valid.
at IBM.Data.DB2.iSeries.iDB2Command.verifyConnection()
at IBM.Data.DB2.iSeries.iDB2Command.ExecuteDbDataReader(CommandBehavior behavior)
at IBM.Data.DB2.iSeries.iDB2Command.ExecuteReader()
at test04.DBDB2.read() in
c:\Users\mikeb\projs\ClassLibrary1\ClassLibrary1\DBDB2.cs:line 27
My line 27 is the call to cmd.ExecuteReader()
Any ideas please?
19 Nov Further thoughts:
[ Please excuse any clumsy etiquette, I'm a new poster here ]
Am I missing something? I'm thinking there are only 2 things to go
wrong here:
My code. No, too simple, and verified by #MikeWills' post
My connection string
Or could there be something else?
- re IBM.Data.DB2.iSeries.iDB2Command.verifyConnection()
Does someone here have access to the code to say what this method does, and what might be causing it to fail?

Solved. I was missing the following:
need to add conn.Open() after conn= new ....
Add CheckConnectionOnOpen=true; to connection string
Remove / from query string

See if this sample helps you out. I have written a library to make IBM server connections easier, this is a very old version of that library. I need to get the new version somewhere public again.
Update: My connection string is: DataSource=127.0.0.1;DefaultCollection=LIBRARY;Naming=sql;UserID=USER;Password=PASSWORD;

Related

Why MySQL throws Exception when I launch my program first time: Error reading from the stream

Authentication to host '127.0.0.1' for user 'root' using method 'mysql_native_password' failed with message: Reading from the stream has failed.
I've searched a lot about this issue and only Internet disconnect solved the problem. Why is that?
I use MYSQL 8 and C# winforms.
Connection code looks like this:
MySqlConnection conn = new MySqlConnection("datasource=127.0.0.1;username=root;password=password;database=my_tests");
The every next try I execute the command is successful! It happens only first time.
I very appreciate your time people. And would be very thankful for constructive help for a newbie like me.
When I put SslMode=None to a string so it looks like
MySqlConnection conn = new MySqlConnection("datasource=127.0.0.1;username=root;password=password;database=my_tests;SslMode=None");
the problem is gone. But I'm not sure if I want not to use it. Any other solutions would be great.
try this code you can use the server ip address instead of local
string connectionString = "server=(local)\SQLExpress;database=my_tests;password:qwerty;integrated Security=SSPI;";
SqlConnection _con = new SqlConnection(connectionString)

Am the ODBC driver of MS Access .md and .accdb files only can handle 64 executions?

Im writing a C# program where i need to use the Odbc api to connect to a .mdb database file.
After the planning, implementation and tests, now theres a BIG problem.
It seems to be, that the MS Access driver can only handles exact 64 executions.
After that, the program has to restart.
Can someone confirm this issue?
Or were there other drivers, which were also more performant?
Greetings .. :)
After the idea of checking the cleanups of the resources, i got the answer .. -.- :
The "using" directive from C# to handle resources had no affect on the OdbcConnection object.
You have to call the Disponse method right before the next closing bracket.
This closing bracket calls the Disponse method, but - I REALLY DONT KNOW WHY - this had no affect.
using (OdbcConnection conn = new OdbcConnection(string.Format(connStr, odbcDriver,
dbq, pwd)))
{
conn.Open();
Console.WriteLine($"Conn Create");
await using OdbcCommand cmd = conn.CreateCommand();
await cmd.CommandText = "select * from [testmodel];";
cmd.Prepare();
DbDataReader reader = cmd.ExecuteReader();
Console.WriteLine($"DB EXEC COUNT '{i}'");
await conn.DisposeAsync();
}
I tried out pyhons pyodbc to reproduce, that it is not a language issue .. well
it worked fine..
with pyodbc.connect(f"Driver={dbAccessDriver};Dbq={dbFilePath};Pwd={dbPassword}") as conn:
conn: pyodbc.Connection
cmd: pyodbc.Cursor = conn.cursor()
cmd.execute("insert into [testmodel] values (?, ?)", (i, "Name " + str(i)))
cmd.commit()
Greetings to all programmers ..
Update 19.01.2021
Well, my last answer wasnt as correct as I expect.
I thought i had solved this problem, but its not.
Actually, my last solution has based on the disposed method after the using syntax of the connection and that has to work, because the triggered Disposed event is always the same.
The corrent solution is:
The problem is caused by reading from a table.
If reader were not closed OR disposed, this caused the error.
If you want to control the connections you have to go deeper and control read and write operations.

How to Select an out parameter from a MySql Procedure in .net

Assume we have a stored procedure like so
CREATE PROCEDURE CopyValue(IN src INT, OUT dest INT)
BEGIN
SET dest = src;
END
I want to call this from a .net app (assume connection etc created successfully)
var sql = "call CopyValue(100, #destValue); select #destValue as Results;";
The string in the above statement works perfectly well when called in MySql Workbench.
However this - obviously - fails with "MySqlException: Parameter '#destValue' must be defined" when executed on a MySqlCommand object in .net
How do I arrange this statement so I can capture an output parameter from an existing procedure?
NB: I'm running against MySql 5.6, which I can't upgrade at this time.
NB Calling the procedure directly with CommandType.StoredProcedure goes against company guidelines.
By default, user-defined variables aren't allowed in SQL statements by MySQL Connector/NET. You can relax this restriction by adding AllowUserVariables=true; to your connection string. No modifications to your SQL or how you're executing the MySqlCommand should be necessary.
For information about why this is the default, you can read the research on this MySqlConnector issue (which also has the same default behaviour, but a much better error message that will tell you how to solve the problem): https://github.com/mysql-net/MySqlConnector/issues/194
A colleague (who wishes to remain anonymous) has answered this perfectly. Essentially put backticks ` after the # and at the end of the variable name e.g.
#`MyParam`
A fully working example.
static void Main(string[] args)
{
using var con = new MySql.Data.MySqlClient.MySqlConnection("Data Source=localhost; User Id=...;Password=...;Initial Catalog=...");
con.Open();
using var cmd = con.CreateCommand();
cmd.CommandText = "call CopyValue2(100, #`v2`); select #`v2` as Results;";
using var reader = cmd.ExecuteReader();
if (reader.Read())
Console.WriteLine($"Copied Value {reader.GetInt64(0)}");
}
Thanks OG :)

Unspecified Error when trying to ExecuteReader on SQL Server CE

I had implemented a database storage on my app for Windows Mobile 6.5 using SQL Server CE.
Had managed to install the SQL Server CE CAB file on the device (Motorola MC65).
Managed to create database file, and create tables. Insert also can be executed.
However when I try to run ExecuteReader() to read records, I hit the following error:
Error Code: 80004005
Message : Unspecified error
Minor Err.: 25534
Source : SQL Server Compact ADO.NET Data Provider
No idea why this is happening. Since insert can be executed I thought this should not be a connection or privilege issue.
The reading code is as below:
openConnection();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT NAME FROM GROUP_INFO ORDER BY NAME ";
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string groupName = reader.GetString(0);
listGroup.Add(groupName);
}
The exception is thrown on the line where cmd.ExecuteReader() is executing.
Any pointers are appreciated. Thanks.
Implement proper error handling for SqlCeExceptions! The error is documented here https://technet.microsoft.com/en-us/library/ms172350(v=sql.110).aspx
Large objects (ntext and image) cannot be used in ORDER BY clauses.
Maybe you should redefine the column as nvarchar(4000) (it is currently ntext), or rephrase the query using:
ORDER BY CAST(Name as nvarchar(4000))
But this will cause a table scan

INSERT query OleDB C#

I know it was 1000000000 times already, but none solution helped to me.
I want to insert data in C# using OleDB. I tried mln solutions but here is the easiest one which should work but it doesn't:
SQLCONNECTION = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\dbScenariusz.mdb";
using (OleDbConnection connection = new OleDbConnection(SQLCONNECTION))
{
string sql = "INSERT INTO Table (content) VALUES('lala')";
connection.Open();
OleDbCommand command = new OleDbCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
SQLCONNECTION is ok. It works fine for the SELECT query.
string sql - I tried this query in Access and it works fine.
I get no error. It just didn't insert anything to the database.
When I run the query in Access (the same database) the row is inserted.
The strange thing is that command.ExecuteNonQuery(); returns 1! That means that 1 row was affected!
I really have no idea where the problem is, so I really appreciate any help.
Sorry for my english.
UPDATE: Another strange thing. I change query to update and it works fine! really wtf? :)
You are connecting to the DataDirectory. Is the .mbd file being copied after the build? In other words are you re-deploying the database with each build and thereby losing the inserts?
A quick test could be using the same code and same connection to do a select after the insert.
In the solution Explorer, check app.config. Double click the app.config, then re-enter the connectionString. Give the path of your database.
For example, in my project the default location of connectionString is:
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\App_Data\database.accdb;Persist Security Info=True"
Suppose the database is stored in this location:
C:\Documents and Settings\Amuk\My Documents\Visual Studio 2010\Projects\insertion\insertion\App_Data
therefore, replace the connectionString with
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Amuk\My Documents\Visual Studio 2010\Projects\insertion\insertion\App_Data\database.accdb;Persist Security Info=True"
your problem will be solved, i hope this will definitely help you, i was also getting the same problem, and by replacing the connectionString with original path, the database is storing all records.
You can try to use transaction to commit your changes.
command.Transaction = connection.BeginTransaction(); //after connection.open()
Then add
command.Transaction.Commit(); //Before connection.close()

Categories