I wrote code to connect to the NETEZZA database. When a response is received, the first line of the result disappears, i.e. only 9 of 10 lines are displayed. I read that there are such problems with the OLEDB driver, but I could not resolve the issue myself.
I tried to add the parameter HDR = YES
class SQL_zapros
{
private string connString = "Provider=NZOLEDB;Password=PASSWORD; User ID=LOGIN; Data Source=127.0.0.1; Initial Catalog=SYSTEM; Persist Security Info=True;";
public string sqlcomm = "";
public DataTable exeReader(string cmd, OleDbParameter[] param)
{
OleDbConnection oConn = new OleDbConnection(connString);
OleDbCommand oCmd;
OleDbDataReader oReader;
DataTable AppData = new DataTable();
oConn.Open();
oCmd = oConn.CreateCommand();
oCmd.CommandText = cmd;
try
{
oReader = oCmd.ExecuteReader();
if (oReader.Read())
{
AppData.Load(oReader);
oReader.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
oConn.Close();
return AppData;
}
}
I want to get all the rows from the database
oReader.Read() reads the first line of the result. AppData.Load also does that, the first line of the result is ignored. To fix it remove the if block, just pass the reader directly.
Also use using blocks when creating instances where the type implements IDisposable. This ensures the resources are always released even in the event of an exception.
public DataTable exeReader(string cmd, OleDbParameter[] param)
{
using(OleDbConnection oConn = new OleDbConnection(connString))
{
DataTable AppData = new DataTable();
oConn.Open();
var oCmd = oConn.CreateCommand();
oCmd.CommandText = cmd;
try
{
using(var oReader = oCmd.ExecuteReader()) {
AppData.Load(oReader);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
return AppData;
}
I would recommend to use OleDbDataAdapter instead. Try like:
...
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(cmd, oConn);
adapter.Fill(AppData);
...
Related
I'm attempting to update a SQL table from C# project datagridview "Work_Table". However when I attempt to make the update I get this error
"Update unable to find TableMapping ['Work_Table'] or DataTable 'Work_Table'"
Any ideas?
Here is my code below:
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = #"Select * from person.addresstype";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dAdapter.Update(ds, "Work_Table");
MessageBox.Show("Saved");
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
You need to retrieve the DataTable from the .DataSource property of the grid. This will have the information on what was added, updated and deleted.
You can skip the command and pass the select string and connection string directly to the DataAdapter constructor.
Create a CommandBuilder to provide the Insert, Update and Delete text for the DataAdapter.Update. Pass the DataAdapter to the constructor of the CommandBuilder.
private string connString = "Your connection string";
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
try
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter("Select * from person.addresstype", connString))
using (SqlCommandBuilder cb = new SqlCommandBuilder(dAdapter))
{
dAdapter.Update(dt);
}
MessageBox.Show("Saved");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";
I´m asking how to connect two or more tables from an MS Access table into c# Windows forms?.
I get the error, that ue cant find the second table:
public partial class Form1 : Form
{
private OleDbConnection connection = new OleDbConnection();
private OleDbConnection connection2 = new OleDbConnection();
public Form1()
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\MitarbeiterDaten2.accdb;
Persist Security Info=False;";
connection2.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\DatenbankAbteilung.accdb;
Persist Security Info=False;";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader["ABTEILUNG"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
}
Anybody got an solution?
Its just about, how to connect two or more MS Access tables into C# Windows forms.
You can reuse the the objects, and can get data from various tables or databases, as :
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader("ABTEILUNG").ToString());
}
reader.Close(); //' Always Close ther Reader. Don't left it open
connection2.Open();
command.Connection = connection2; //' Reusing Same Command Over New Connection
command.CommandText = "Select Field2 from Table2";
while (reader.Read)
{
if (!(Convert.IsDBNull(reader("Field2")))) //' Checking If Null Value is there
{
Abteilung.Items.Add(reader("Field2").ToString());
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
connection2.Close();
}
}
How about using using blocks to take care of the commands and connections and then using DataAdapter to get the job done easily. I use some code like this.
DataSet ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(MDBConnection.ConnectionString))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT Column FROM Table1", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
using (OleDbCommand cmd = new OleDbCommand("SELECT AnotherColumn FROM Table2", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;
I want to get the result from a query in my oracle database and put it in a gridview. Now my problem is, I have no idea how to output it in the gridview. I am using the gridview from the toolbox and my oracle connection is working. I also have the right SELECT query and I can output that in a listbox. I just have no idea how to do this in a gridview. I looked for it and I came across this: How to populate gridview with mysql? Although this doesn't help me.
How can I output it in a gridview so that it looks exactly the same as a normal table in the oracle database?
What should I use and how?
This is my code:
public void read()
{
try
{
var conn = new OracleConnection("")
conn.Open();
OracleCommand cmd = new OracleCommand("select * from t1", conn);
OracleDataReader reader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
while (reader.Read())
{
var column1 = reader["vermogen"];
column = (column1.ToString());
listBox1.Items.Add(column);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To bind a DataTable to a DataGridView your code need simply to be changed to
public void read()
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The OracleDataReader could be passed to the Load method of the DataTable and then the table is ready to be bound to the DataGridView DataSource property. I have also added some using statement to ensure proper disposing of the disposable objects employed. (In particular the OracleConnection is very expensive to not close in case of exceptions)
You can use DataSet too:
public void read()
{
try
{
OracleConnection conn = new OracleConnection("");
OracleCommand cmd = new OracleCommand("select * from t1", conn);
conn.Open();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
First establish connection in case, you didnt establish globally by using connection string. Then use oleDbcommand for the oracle sql command you want to execute. In my case, it is 'select * from table_name' which would show all data from table to datagrid. I wrote this code in a button to display data on data grid.
{
OleDbConnection conn = new OleDbConnection("");
OleDbCommand cmd = new OleDbCommand("select * from table_name", conn);
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
conn.Close();
}
}
I am using the below code to access the MS Access Database. But i got a error message Fill: SelectCommand.Connection property has not been initialized.How can i solve this issue.
common.cs
=========
public static bool DBConnectionStatus()
{
try
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_admin.mdb; Jet OLEDB:Database Password=admin";
using (OleDbConnection conn = new OleDbConnection(conString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
}
catch (OleDbException)
{
return false;
}
protected void btn_general_Click(object sender, EventArgs e)
{
try
{
bool state = common.DBConnectionStatus();
if (state == true)
{
cmd = new OleDbCommand("select * from tbl_admin");
da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds); // Error Here
if (ds.Tables[0].Rows.Count > 0)
{
}
}
}
catch (Exception e1)
{
}
}
I did suggest you to modify your code to something like this:
private DataTable YourData()
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_admin.mdb; Jet OLEDB:Database Password=admin";
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(conString))
{
try
{
conn.Open();
SqlCommand command = new SqlCommand("select * from tbl_admin", conn);
command.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
// do somethign here
}
}
catch (Exception)
{
/*Handle error*/
}
}
return ds.Tables[0];
}
And then:
protected void btn_general_Click(object sender, EventArgs e)
{
this.YourData(); // you will get the Data here. you can then use it the way you want it
}
You are initializing a Command which you use to construct a DataAdapter, but both without setting the required Connection property:
cmd = new OleDbCommand("select * from tbl_admin"); // <-- no connectuion assigned
da = new OleDbDataAdapter(cmd); // <-- no connectuion assigned
So your exception is pretty self-explanatory.
One final note: using will dispose/close the connection, so the method DBConnectionStatus is pointless. So don't use it, instead use the using in in the first place:
try
{
using(var con = new OleDbConnection(connectionString))
using(var da = new OleDbDataAdapter("elect * from tbl_admin", con))
{
var table = new DataTable();
da.Fill(table); // note that you don't need to open the connection with DataAdapter.Fill
if (table.Rows.Count > 0)
{
// ...
}
}
}
catch (Exception e1)
{
// don't catch an exception if you don't handle it in a useful way(at least loggging)
throw;
}
As per your requirement you can also use SqlDataAdapter instand of ExecuteReader.
public void ReadMyData(string connectionString)
{
string queryString = "SELECT OrderID, CustomerID FROM Orders";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + ", " + reader.GetString(1));
}
// always call Close when done reading.
reader.Close();
}
}