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();
}
}
Related
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);
...
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 am writing a c# windows forms application and i am coming accross the error mentioned above. I think this is happening because i am opening an sql connection and reader object in my main form load object and then doing the same thing again in another click event handler. I am not sure what i need to do in order to change my code / stop this from happening (or if this is even the problem). I have tried turning MARS on in my connection string but this did not fix the problem. Below is my code.
namespace Excel_Importer
{
public partial class Export : Form
{
public Export()
{
InitializeComponent();
}
private void cmbItemLookup_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Export_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings ["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From ExportItem", conn);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ExportItemName", typeof(string));
dt.Load(rdr);
cmbItemLookup.DisplayMember = "ExportItemName";
cmbItemLookup.DataSource = dt;
conn.Close();
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn);
SqlDataReader rdr2;
rdr2 = cmd2.ExecuteReader();
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
You need to close your DataReaders. They implement the IDisposable interface, so the simplest thing is to put them inside a using block:
using (rdr = cmd.ExecuteReader())
{
..
} // .NET always calls Dispose() for you here
Actually, you pretty much have to dispose of everything that implements IDisposable, or problems gonna happen.
As the other answer points out, you must tidy up your clicked event code:
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString) )
{
conn.Open();
using(SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn) )
{
using(SqlDataReader rdr2= cmd2.ExecuteReader())
{
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
}
I have 2 tables in MySql (privacy , lawsuit_under_500) ,
In privacy i have 2 columns (id , nameofcase ) ,
In lawsuit_under_500 4 columns(id,nameofcase,priceone,pricetwo) ,
I make a form with a datagridview and i want to execute this query :
select privacy.id,lawsuit_under_500.id,privacy.nameofcase, lawsuit_under_500.priceone, lawsuit_under_500.pricetwo
From privacy inner join lawsuit_under_500
where lawsuit_under_500.id=5 and privacy.id=1 || lawsuit_under_500.id=1 and privacy.id=2 || lawsuit_under_500.id=10 and privacy.id=3
ORDER BY privacy.id
In the form i have:
public Form55()
{
InitializeComponent();
}
private void Form55_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I have put the tables in my DataSet but I cant figure out how to make it. I tried to make privacyBindingSourse in the datagridview and i added manually 2 buttons for priceone and pricetwo put i cant put the query so i can get the information.
Any ideas/help how to make it ?
BEFORE YOU ANSWER IF YOU HAVE ANY QUESTION PLEASE ASK ME
using MySql.Data.MySqlClient;
MySqlConnection conn = new MySqlConnection("Your MY SQL connection");
MySqlCommand cmd = new MySqlCommand("Your Mysql query");
MySqlDataReader dr=cmd.ExecuteReader();
gridview1.datasource=dr;
gridview1.databind();
// try this also
connectionString = "Your Connection";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("Your Query", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
//close connection
this.CloseConnection();
}
I made it with this way
private void Form56_Load(object sender, EventArgs e)
{
try
{
MySqlConnection cnn = new MySqlConnection("MY CONNECTION");
cnn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("MY QUERY", cnn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
}
static public SqlCeConnection OpenSQL()
{
SqlCeConnection cncount = new SqlCeConnection(#"Data Source = " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Database.sdf; Password =''");
return cncount;
}
static public DataTable DoSelect( string strSQL)
{
SqlCeConnection cn = OpenSQL();
DataTable dtRetValue = new DataTable();
using (SqlCeDataAdapter da = new SqlCeDataAdapter())
{
using (SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = strSQL;
da.SelectCommand = cmd;
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
try
{
//using (SqlCeDataReader reader = da.SelectCommand.ExecuteReader())
SqlCeDataReader metsDr = da.SelectCommand.ExecuteReader();
dtRetValue.Load(metsDr);
return dtRetValue;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error - DoSelect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return null;
}
}
}
}
Insert in Button
string sql1 = "YOURE QUERY ";
DataTable dt1 = SQLcode.DoSelect(sql1);
dgvcompany.DataSource = dt1;
I know how to connect, open, read, close as you see below. I also have awesome tutorial how to add update/delete etc.
I can connect dataTable to sql using asp.net controls, but I want to learn how to manipulate it from C#.
MasterCust is my gridview table name. How do I connect the to it?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection("Data Source=aserver;Initial Catalog=KennyCust;Persist Security Info=True;user id=sa;pwd=qwerty01");
SqlDataReader rdr = null;
string commandString = "SELECT * FROM MainDB";
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
rdr = Cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Conn != null)
{
Conn.Close();
}
}
//MasterCust.
//MasterCust.DataSource = commandString;
//MasterCust.DataBind();
}
Edit: This code worked
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
SqlDataAdapter sdp = new SqlDataAdapter(Cmd);
DataSet ds = new DataSet();
sdp.Fill(ds);
//rdr = Cmd.ExecuteReader();
MasterCust.DataSource = ds.Tables[0];
MasterCust.DataBind();
}
Set the GridView's Datasource property and simply call the DataBind method.
This code will work. ( Tested)
SqlConnection Conn = new SqlConnection("Data Source=Localhost\\SQLEXPRESS;Initial Catalog=Flash2;Integrated Security=True;");
SqlDataReader rdr = null;
string commandString = "SELECT * FROM USER_MASTER";
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
rdr = Cmd.ExecuteReader();
MasterCustView.DataSource = rdr;
MasterCustView.DataBind();
}
catch (Exception ex)
{
// Log error
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Conn != null)
{
Conn.Close();
}
}