I am new in C-Sharp, i am trying to access my Database from C-Sharp, i have written the following code, and i dont know what to write next to view data. I have searched this on net but didnt get much. Kindly tell me this in easy code.
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbConnection conn = new OleDbConnection(connection);
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.SelectCommand = cmd;
Refer following code:
string strProvider = "#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;
Hope its helpful.
Try this
try
{
Dataset myDataSet=new Dataset();
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd );
connection .Open();
myDataAdapter.Fill(myDataSet,"TableName");
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
connection .Close();
}
Remember for good coding practice ,always connection should be open in Try Block
and closed in Finally Block
Related
I am getting this error "There is already an open DataReader associated with this Connection which must be closed first". I have tried using command but still can't fix this issue. The code I am using is as follows
{
conn.Open();
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
using (MySqlDataAdapter MyAdapter = new MySqlDataAdapter())
{
MyAdapter.SelectCommand = cmd;
using (DataTable dTable = new DataTable())
{
MyAdapter.Fill(dTable);
GridView1.DataSource = dTable;
}
}
}
I was originally trying below code (without using command).
conn.Open();
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = cmd;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
GridView1.DataSource = dTable;
conn.Close();
But both of the codes are giving exactly the same error (i.e. There is already an open DataReader associated with this Connection which must be closed first.)
Your help would be really appreciated.
Thanks in advance!
Usage of dataset will be more handy and efficient rather than table.Even you can cache it.
Also no need to use using construct because MySqlAdapter's fill method does it everything for you like
i)Open the connection. ii)Read the command ii)Execute the command ii)close the connection
using ()
{
if(Cache["mydata"]==null)
{
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = cmd;
DataSet ds =new DataSet();
MyAdapter.Fill(ds);
Cache["mydata"]=ds;
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
GridView1.DataSource = (DataSet)Cache["mydata"];
GridView1.DataBind();
}
}
This line creates a DataReader that you're not closing:
cmd.ExecuteReader();
Just remove the whole line, it's useless in your case.
I have an openquery SQL script:
Select * from openquery([oak],'
SELECT LicenseKey, SUM(PaymentAmount)as Payments
FROM vw_ODBC_actv_Payments pt
WHERE MONTH(pt.EntryDate) = 2 and
YEAR(pt.EntryDate) = 2015
GROUP BY LicenseKey
')
When I run this from SSMS I can see that it returns expected n rows.
However when I'm firing this with the same connection properties to get the data in a DataSet for a C# console application:
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand pcmd= new SqlCommand();
DataSet ds= new DataSet();
OpenConnection();
pcmd.Connection = new SqlConnection("Data source=IP adress of the server;Initial Catalog=master; user ID=***; password=***");
cmd.CommandText = "Select * from openquery([oak],'" +
"SELECT LicenseKey, SUM(PaymentAmount)as Payments" +
"FROM vw_ODBC_actv_Payments pt " +
"WHERE MONTH(pt.EntryDate) = 2 and" +
"YEAR(pt.EntryDate) = 2015" +
"GROUP BY LicenseKey')";
try
{
da.SelectCommand = pcmd;
da.Fill(ds); //here comes the error
}
catch (Exception ex)
{
throw new Exception("DBUtils.ExecuteReader():" + ex.Message);
}
I'm getting an error like this:
The provider indicates that the user did not have the permission to
perform the operation. Now I need to do something with this issue
I'm just learning about openquery. Can anybody guide?
Firstly you're not opening the connection anywhere in your code hence the error. Second clean up your code with the using block. So assuming the query works as required you can do something like.
using(SqlConnection con = new SqlConnection("Connection String Here"))
{
string myQuery = "Your Query";
using(SqlCommand cmd = new SqlCommand(myQuery, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
}
}
}
Note: It would be a better if you stored the connectionString in your config file and read it in your code.
private void toolStripButton1_Click(object sender, EventArgs e)
{
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=mdc;" +
"Uid=root;" +
"Pwd=;";
OdbcCommand cmd = new OdbcCommand("select * from tbl_delivery");
cmd.CommandType = CommandType.Text;
DataSet dt = new DataSet();
OdbcDataAdapter ds = new OdbcDataAdapter();
ds.Fill(dt);
tbl_deliveryDataGridView.DataSource = dt;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
there is always an error everytime i am going to run the program, i don't know where is the error. i tried editing the code yet still the error keeps on popping out.
You getting error because you haven't assign OdbcCommand to OdbcDataAdapter and trying to execute Fill method. you should assign OdbcCommand to OdbcDataAdapter like this
OdbcDataAdapter ds = new OdbcDataAdapter(cmd,conn);
And then try to Fill DataTable
conn.Open();
DataSet dt = new DataSet();
OdbcDataAdapter ds = new OdbcDataAdapter();
ds.Fill(dt);
tbl_deliveryDataGridView.DataSource = dt;
I am getting
"No value given for one and more required parameter"
from below code everything looks fine not able to find the problem.
string myConnectionString= #"Provider=Microsoft.Jet.OLEDB.4.0; Data source=D:\TiptonDB.mdb";
string query = "SELECT NodeID FROM NDDINodes";//"SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
DataSet dt = new DataSet();
using (OleDbConnection myConnection = new OleDbConnection())
{
myConnection.ConnectionString=myConnectionString;
OleDbCommand cmd=new OleDbCommand ();
cmd.Connection=myConnection;
// cmd.CommandText="SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
myConnection.Open();
OleDbDataAdapter ad = new OleDbDataAdapter(query,myConnection);
ad.Fill(dt);
}
string myConnectionString= #"Provider=Microsoft.Jet.OLEDB.4.0; Data source=D:\TiptonDB.mdb";
string query = "SELECT NodeID FROM NDDINodes";//"SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
DataSet dt = new DataSet();
OleDbConnection objXConn = new OleDbConnection(myConnectionString);
objXConn.Open();
OleDbCommand objCommand = new OleDbCommand(query, objXConn);
OleDbDataAdapter adp = new OleDbDataAdapter(objCommand);
adp.Fill(dt);
objXConn.Close();
Make sure your connection string isn't missing data: UserName/Password, Persist Security Info=True,...
Check this link for access connectionString settings.
just add this in your code
OleDbDataAdapter ad = new OleDbDataAdapter();
ad.SelectCommand = new OleDbCommand(query, myConnection);
I'm trying show a DataGrid in C# (for app WindowsMobile). I have a database ("pruebaDB.sdf") in DataConnections and one table ("tablaMercancia").
Also in DataSource I have "pruebaDBDataSet" and "tablaMercancia".
How I can show data table in a DataGrid?
I use a SmartDevice project (I can't to use DataGridView, only I use DataGrid).
I can show a new table (created for code) in a DataGrid, but I don't know to show an existing table in my database.
string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\pruebaDB.sdf;Persist Security Info=False";
SqlCeConnection connection = new SqlCeConnection(conSTR);
string sql = "SELECT * FROM tablaMercancia";
connection.Open();
SqlCeCommand cmd = new SqlCeCommand(sql, connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
//...............
//...Any idea?
//...............
connection.Close();
Any ideas please?
Thanks!!!
Please, Change Datagridview name as per below :
string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\pruebaDB.sdf;Persist Security Info=False";
SqlCeConnection connection = new SqlCeConnection(conSTR);
string sql = "SELECT * FROM tablaMercancia";
connection.Open();
SqlCeCommand cmd = new SqlCeCommand(sql, connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds=new DataSet();
da.Fill(ds);
//datagridview1 is name of datagridview in form:
datagridview1.DataSource=ds.Tables[0];
connection.Close();
Try this.
string sql = "SELECT * FROM tablaMercancia";
connection.Open();
//SqlCeCommand cmd = new SqlCeCommand(sql, connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(sql, connection);
DataSet ds=new DataSet();
da.Fill(ds);
designing page track the gridview or data grid
1st use namespace using System.Data,SqlClient;
sqlconnection con=new sqlconnection("string path");
con.open();
sqldataadapter da=new sqldataadapter("select * from emp",con);
dataset ds=new dataset();
da.fill(ds,"emp");
gridview1.datasource=ds;
gridview1.databind();