I'm trying to connect to a AS400 server using ODBC driver via vb.net application but the problem is that I am trying to fill a dataset and whenever I want to display the data I don't find any thing
This is my code:
Dim cn As OdbcConnection
Dim cm As OdbcCommand
Dim dm As OdbcDataAdapter
Sub ConnServer()
Try
cn = New OdbcConnection("DSN=AS400_CA;UID=root;PWD=*****;")
cn.Open()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Ecriture Comptable")
End Try
End Sub
Public Function GetData(query As String) As DataTable
Try
cn = New OdbcConnection("DSN=AS400_CA;UID=root;PWD=*****;")
Dim cmd As OdbcCommand = New OdbcCommand(query, cn)
cn.Open()
Dim ds = New DataSet()
cmd.Connection = cn
dm.SelectCommand = cmd
dm.Fill(ds, "table")
Dim data = ds.Tables("table")
cn.Close()
Return data
Catch ex As Exception
con.Close()
Return New DataTable()
End Try
End Function
```
I do not know what provider you are using. Check https://www.connectionstrings.com/as-400/ to check your connection string. I do not see a connection string that matches the syntax of your string.
I have no idea of select strings in AS400 so I just used a standard Sql string. Put your try/catch in the UI code so you can show a message box with the error.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable
Try
dt = GetData("Select * From SomeTable;")
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
DataGridView1.DataSource = dt
End Sub
In your function you are returning a DataTable so why are you messing with a DataSet? Just load the DataTable. Connections, Commands, and DataReaders all need to be disposed. Using...End Using blocks handle closing and disposing even if there is an error.
Public Function GetData(query As String) As DataTable
Dim dt As New DataTable
Using cn = New OdbcConnection("DSN=AS400_CA;UID=root;PWD=*****;"),
cmd As OdbcCommand = New OdbcCommand(query, cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
this C# code worked for me.
I am using the IBM access client solutions 64bit ODBC driver.
using System;
using System.Data.Odbc;
using System.Data;
namespace IntroUI
{
class Program
{
static void Main(string[] args)
{
// make sure using 64 bit IBM i Access ODBC driver
var conn = OpenConnection("dsn", "user", "pass");
OdbcCommand cmd = conn.CreateCommand();
var query = "select a.* from qrpglesrc a";
var table = GetData( conn, query ) ;
var numRows = table.Rows.Count ;
for( var ix = 0 ; ix < numRows ; ++ix )
{
var row = table.Rows[ix] ;
var srcdta = row.ItemArray[2] ;
Console.WriteLine( srcdta ) ;
if ( ix > 20 )
break ;
}
conn.Close( ) ;
}
// InDsn is the dsn from the odbc administration window
static OdbcConnection OpenConnection( string InDsn, string InUser, string InPwd )
{
string connString = "DSN=" + InDsn + "; UID=" + InUser +
"; PWD=" + InPwd + ";" ;
OdbcConnection conn = new OdbcConnection( connString ) ;
conn.Open( ) ;
return conn ;
}
static DataTable GetData( OdbcConnection conn, string query )
{
OdbcDataAdapter dm = new OdbcDataAdapter() ;
OdbcCommand cmd = new OdbcCommand(query, conn);
DataSet ds = new DataSet( ) ;
dm.SelectCommand = cmd ;
dm.Fill( ds, "table") ;
var data = ds.Tables["table"] ;
return data ;
}
}
}
Related
I have different tables on same database , and i need to insert ID's of data from combobox.
Here's client table
what i need is to get id from combobox selected item and put it on the final table,
this is what i try
cmd.Parameters.AddWithValue("Client", client.Text)
Private Sub livbtn_Click(sender As Object, e As EventArgs) Handles livbtn.Click
'ModePaiement()
Try
SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client "
Execute(SQL, "Insert")
MessageBox.Show("The record has been saved.", "",
MessageBoxButtons.OK, MessageBoxIcon.Information)
ResetMe()
Catch ex As Exception
MessageBox.Show("" & ex.Message, "",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
and not working for sure , please help !
here's Module data connection:
Option Explicit On
Option Strict On
Imports System.Data.OleDb
Module AccessDB_Connection
Public Function GetConnectionString() As String
Dim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" & Application.StartupPath & "\BLdatabase.accdb;Persist Security Info = false;"
Return strCon
End Function
Public con As New OleDbConnection(GetConnectionString())
Public cmd As OleDbCommand
Public SQL As String = String.Empty
Public Function PerformCRUD(Com As OleDbCommand) As DataTable
Dim da As OleDbDataAdapter
Dim dt As New DataTable()
Try
da = New OleDbDataAdapter
da.SelectCommand = Com
da.Fill(dt)
Return dt
Catch ex As Exception
MessageBox.Show("" & ex.Message)
End Try
Return dt
End Function
End Module
thank's everybody for replying;
so here's execute method :
Private Sub Execute(MySQL As String, Optional Parameter As String = "")
cmd = New OleDbCommand(MySQL, con)
AddParameters(Parameter)
PerformCRUD(cmd)
End Sub
Private Sub AddParameters(str As String)
cmd.Parameters.AddWithValue("Client", client.Text)
End Sub
Public Function PerformCRUD(Com As OleDbCommand) As DataTable
Dim da As OleDbDataAdapter
Dim dt As New DataTable()
Try
da = New OleDbDataAdapter
da.SelectCommand = Com
da.Fill(dt)
Return dt
Catch ex As Exception
MessageBox.Show("" & ex.Message)
End Try
Return dt
End Function
so it's very simple , i need to store an id value from an selected item :
enter image description here
here's an example , i need to store that value 26 from that table client to other table when i select IMAX client from combobox
enter image description here
enter image description here
there's 2 different results it depends on the query used :
with SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client " --> there's nothing happened
with SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) values(SELECT code_client from client WHERE client = #Client) "
--> error
enter image description here
The issue I see, you are trying to run:
SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client "
However, in your PerformCRUD method, you are filling a data adapter and returning a DataTable based on an INSERT where ExecuteNoQuery is the method to use.
Here is an example (More Info):
Using cmd = con.CreateCommand()
cmd.CommandText = SQL
'It is good practice to specify the data type. Note: 80 in this example is the column size/length.
cmd.Parameter.Add("#Client", OleDbType.VarChar, 80).Value = client.Text
cmd.Connection = con
con.Open() 'if not already open
cmd.ExecuteNonQuery()
End Using
hi so i have this list that im currently using on a combobox that's why i have the idcategoria = 0 with the nomeCategoria = "Select your Category"so the combobox default item would be "select your category".
here is the code of the list
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = 0
p.NomeCategoria = "select your category"
lstTodos.Add(p)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
Now i want to use the same list on a datagridview and i wanted to know if there is a way to not show the id = 0 on the datagridview or do i have to create another list without the idCategorie = 0 for the datagridview, any ideas on this? thanks
Create another list from already loaded
Dim newList = lstTodos.Skip(1).ToList()
Skip method will return new collection without first item.
Notice that this approach will work only when - Select your Category - item is a first item in the list.
Or change your method to return list without - Select your Category - item and add it only when you need.
Public Shared Iterator Function ObterTodosC() As IEnumerable(Of Ccategoria)
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Yield New Ccategoria With
{
.IdCategoria = reader.GetInt32(0),
.NomeCategoria = reader.GetString(1)
}
End While
End Using
End Using
End Function
Then you can create list of categories for datagridview
Dim forDataGridView = ObterTodosC().ToList()
Dim notSelectedCategory As New Ccategoria With
{
.IdCategoria = 0,
.NomeCategoria = "select your category"
}
Dim forComboBox = forDataGridView.ToList()
forComboBox.Insert(0, notSelectedCategory)
With this approach your remove side effect from ObterTodosC method.
So method responsibility will be only load items from database
I am using an OledbConnection to an AS400 computer. When I have a SQL statement that will return nothing, it just hangs on the adapter command Fill.
Function ExecuteOLEDBQuery(ByVal cmdtext As String) As DataTable
Try
Dim connString As String = "Provider=IBMDA400;Persist Security Info=True;User ID=##USERID;Password=##PASSWORD;Data Source=##SYSTEM"
Dim as400 As New OleDb.OleDbConnection(connString)
Dim cmd As New OleDb.OleDbCommand(cmdtext, as400)
Dim adapter As New OleDb.OleDbDataAdapter(cmd)
cmd.CommandTimeout = 60 'Doesn't work. It never times out.
Dim dt As New DataTable
as400.Open()
adapter.Fill(dt) 'This is where it hangs
as400.Close()
adapter.Dispose()
cmd.Dispose()
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
Any ideas?
It may be the connection to the AS400 itself. Try this version which disposes of the object in a slightly different order:
Function ExecuteOLEDBQuery(cmdtext As String) As DataTable
Using cn = New OleDbConnection("Provider=IBMDA400;Persist Security Info=True;User ID=##USERID;Password=##PASSWORD;Data Source=##SYSTEM")
cn.Open()
Using da = New OleDbDataAdapter(cmdtext, cn)
Dim dt = New DataTable
da.Fill(dt)
Return dt
End Using
End Using
End Function
I have installed Oracle 10g Express Edition database on a server and install the client on my PC.
Now, I`m developing a vb.net application using visual studio 2005 and I need to use the oracle 10g express edition database. So I initialize the connection using the following connection string:
_connectionString = "User Id=Graphya;Password=Graphya;Data Source=gis64:1522/XE;"
Then I define new OracleDataAdapter, and I use the following code to fill a dataset:
Dim insertCommand As OracleCommand = New OracleCommand()
Dim commandTextTemplate As String = "INSERT INTO {0}(" & g_pfldUsername & ", " & g_pfldSubject & ") VALUES (?, ?)"
insertCommand.CommandText = String.Format(commandTextTemplate,TABLE_NAME)
insertCommand.Connection = Me.Connection
insertCommand.Parameters.Add(New Oracle.DataAccess.Client.OracleParameter(g_pfldUsername, Oracle.DataAccess.Client.OracleDbType.Varchar2, 50, g_pfldUsername))
insertCommand.Parameters.Add(New Oracle.DataAccess.Client.OracleParameter(g_pfldSubject, Oracle.DataAccess.Client.OracleDbType.Varchar2, 50, g_pfldSubject))
_OracleDataAdapter.InsertCommand = insertCommand
_OracleDataAdapter.Fill(_dataSet, TABLE_NAME)
So after debugging this code I got the following error:
Unable to cast object of type 'Oracle.DataAccess.Client.OracleCommand' to type 'System.Data.Common.DbCommand'.
#Davideg: my code is c# to fill data set
OleDbConnection cnOra = new OleDbConnection("Provider=MSDAORA;Data Source=myOracleServer;"
+ "user id=myUID;password=myPWD;"
+ "persist security info=false;");
OleDbCommand cmdPerson = new OleDbCommand
+ ("{call PackPerson.allPerson({resultset 3, ssn, fname, lname})}", cnOra);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmdPerson);
cnOra.Open();
DataSet ds = new DataSet();
daPerson.Fill(ds,"Person");
this.dataGrid1.DataSource = ds.Tables["Person"];
cnOra.Close();
Function GetEmailsByPageName(ByVal pageName As String) As DataSet
Dim cn As New OracleConnection
Dim cmd As New OracleCommand
cn = New OracleConnection
cn.ConnectionString = (ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
cmd = New OracleCommand("ORACLEDBA.PACKAGE_EMAIL.SP_EMAIL_LISTING_BY_NAME")
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection = cn
cmd.BindByName = True
Dim paramCursor As OracleParameter = New OracleParameter("email_list_cursor", OracleDbType.RefCursor)
With cmd.Parameters
.Add(New OracleParameter("a_page_name", OracleDbType.Varchar2)).Value = pageName
.Add("a_err_code", OracleDbType.Int32, Data.ParameterDirection.Output)
.Add("a_err_msg", OracleDbType.Varchar2, 300).Direction = Data.ParameterDirection.Output
.Add(paramCursor).Direction = Data.ParameterDirection.Output
End With
Dim da As New OracleDataAdapter(cmd)
Dim dsEmail As DataSet = New DataSet
Try
da.SelectCommand = cmd
da.Fill(dsEmail)
Return dsEmail
Catch ex As Exception
Throw
Finally
da.Dispose()
cmd.Dispose()
cn.Dispose()
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Function
I have a problem refreshing a DataGridView control after Insert or Update. The source code:
Get all rows from table in datatable and set to the datasource:
Dim dt1 as DataTable = GetData("SELECT * FROM CLAIMSTATE ")
dataGrid.DataSource = dt1
Update Event if ID is valued, and Insert if it isn't:
Private Sub dataGrid_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dataGrid.RowLeave
Dim row As DataGridViewRow = CType(sender, DataGridView).Rows(e.RowIndex)
Dim query As New StringBuilder("")
If row.Cells(0).Value & "" = "" Then
query.Append("INSERT INTO CLAIMSTATE ")
query.Append("(CST_CODE, CST_LABEL, CST_POINTS)")
query.Append("VALUES ")
query.Append("(?, ?, ?)")
Else
query.Append("Update CLAIMSTATE ")
query.Append("SET CST_CODE = ?, ")
query.Append("CST_LABEL = ?, ")
query.Append("CST_POINTS = ? ")
query.Append("WHERE CST_ID = ? ")
End If
Dim command As New OdbcCommand(query.ToString(), con)
command.Parameters.Add("#cst_code", OdbcType.Char).Value = row.Cells(1).Value
command.Parameters.Add("#cst_label", OdbcType.NVarChar).Value = row.Cells(2).Value
command.Parameters.Add("#cst_points", OdbcType.Decimal).Value = row.Cells(3).Value
command.Parameters.Add("#cst_id", OdbcType.BigInt).Value = row.Cells(0).Value
Dim res As Integer = ExecuteNonQuery(command)
End Sub
Public Function GetData(ByRef sqlQuery As String) As DataTable
Dim command As New OdbcCommand(sqlQuery, con)
Try
If con.State = ConnectionState.Closed Then
con.ConnectionString = conString
con.Open()
End If
Using dr As OdbcDataReader = command.ExecuteReader()
Dim dt As New DataTable()
dt.Load(dr)
Return dt
End Using
'con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
Return Null
End Try
End Function
Public Function ExecuteNonQuery(ByRef command As OdbcCommand) As Integer
Dim result As Integer = 0
If con.State = ConnectionState.Closed Then
con.ConnectionString = conString
con.Open()
End If
'Dim command As New OdbcCommand(sqlQuery, conn)
Try
'command.Connection = con
'Dim cmd As New OdbcCommand( sqlQuery, conn)
result = command.ExecuteNonQuery()
Catch
result = 0
If con IsNot Nothing Then
con.Close()
command.Dispose()
End If
Finally
command.Dispose()
End Try
Return result
End Function
I tried to get all records from the table and set the datasource again at the end of the method but it doesn't work.
If I put the code:
dataGrid.Rows.Clear()
dataGrid.Columns.Clear()
dt1 = GetData("SELECT * FROM CLAIMSTATE ")
dataGrid.DataSource = dt1
on end of event method RowLeave I recive this error:
"Operation is not valid because it results in a reentrant call to the
SetCurrentCellAddressCore function"
on dataGrid.Rows.Clear(), but if I remove the line codes Rows.Clear() and Columns.Clear(), the debug cursor after execute dataGrid.DataSource = dt1 return to begin of event method an execute some code again and after I recive the some error "...reentrant call to the SetCurrentCellAddressCore function"!
Help me, please!
Here is a C# class I have that I use to connect search my GridView. What you need should be similar I would think.
protected void lbSearch_Click(object sender, EventArgs e)
{
if (txtSearch.Text.Trim().Length > 0)
{
odsInbox.FilterExpression =
string.Format("(l_name LIKE '*{0}*') OR (f_name LIKE '*{0}*') OR (title LIKE '*{0}*')",
txtSearch.Text);
}
else
{
odsInbox.FilterExpression = string.Empty;
}
gvInbox.DataBind();
}
protected void lbClear_Click(object sender, EventArgs e)
{
odsInbox.FilterExpression = string.Empty;
txtSearch.Text = "";
gvInbox.DataBind();
}
I hope this gets you on the right track.
For solving this problem I use OdbcDataAdapter. I save all changes with adapter.Update(dataTable) and after I fill the datatable again: adapter.fill(dataTable).