I have created ODBS user DNS for database, opened VS, created DataSet and imported one table members. I would like to read all records from dataset, how to do that? I have tried query below but it return no result. I can preview data using preview menu in designer but do not find a way to get data using code.
var dataSet = new DataSet1();
var membersDataTable = dataSet.members;
var take = membersDataTable.Take(100);
It looks like you have created the schema for a DataSet, but you have not run any queries to load the DataSet.
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
string queryString = "SELECT * FROM Members";
OdbcDataAdapter adapter =
new OdbcDataAdapter(queryString, connection);
// Open the connection and fill the DataSet.
try
{
connection.Open();
adapter.Fill(dataSet);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
Related
The user enters data in the form. When the save button is pressed, I execute a SQL query to save the data.
I would like to know:
If the user has write access to the database so I can display an error if they don't
If the select/insert statement was successfully executed
My general code looks like this:
string query = "some query text for an insert, select, or update statement";
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
try
{
using (SqlCommand command = new SqlCommand(query, connection))
{
// I am paramterizing the query like this
command.Parameters.AddWithValue("#<param>", <value>);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(dataTable);
}
}
catch (SqlException exception)
{
// Will I get an exception if the user does not have credentials to access this database?
MessageBox.Show("An error occurred trying to save data to SQL: " + exception.Message);
}
connection.Close();
// How do I know if the select/insert was successful?
}
At this point, I look in the DataTable to find the data to display in a DataGridView to the user (for select queries).
I'm developing auction site as my University Final year project.
But I'm stuck in one problem i-e Which I click "View Details" hyperlink in Grid-view, it should compare Sno and Display its complete information present in SQL Server Table in new Tab.
Screenshot of Grid-view
string query1 = "select * from Sell ";
What condition I should apply in the above SQL Query to perform my task
If I understand you question, it sounds like you are wanting to have a link view details link clicked that retrieves the data from you sql database for the specific item being clicked.
If this is the case you are first going to want to get your sql data into a string which takes a couple more steps then what your are attempting in your example.
Instead try using a stored procedure which takes a parameter being the item your fetching and use this model:
public string StringFromDatabase()
{
SqlConnection connection = null;
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Your Connection String Goes Here");
connection.Open();
var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
{
CommandType = CommandType.StoredProcedure
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["Item"].ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
The connection to database is working if I am using SqlDataSource object but it's not working when I am using C# code.
See the error:
http://i.stack.imgur.com/FTLvn.jpg
The problem is the data set returning null while i can track the query on SQL Server profiler.
and i test the query on SQL query editor it returning a result can you told me what the wrong on the code:
Code to return result on Data Set
Code Sample:
static public DataSet GetData(string SqlStatement)
{
DataSet datasetdata=new DataSet();
using (SqlConnection connection =
new SqlConnection(ConfigurationManager.ConnectionStrings["Undp_PortalConnectionString1"].ToString()))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(SqlStatement, connection);
adapter.Fill(datasetdata);
return datasetdata;
}
}
SqlStatement = Select * From Portal_PersonalInfo Where email = 'waleed.obyed#undp.org'
Table :
http://i.stack.imgur.com/jQMnX.jpg
You need to check this while the connection is OPEN - by default, the SqlDataAdapter will open and close the connection as needed - you never get a chance to check while it's open.
If you open the connection yourself
connection.Open();
before the call to .Fill() - then you will see the ServerVersion is quite nicely filled on the connection property:
I found the problem from the DataSet file on the App_Code called DataSet.xsd this file add to datasetdata Table called ES_ICTCR see the photo, i delete this file i think because it has common name DataSet.xsd.
check the Table Count= 2.
http://i.stack.imgur.com/f66JJ.jpg
Im having an issue with the next code:
try
{
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Jet OLEDB:Database Password=LuzDary;");
OleDbDataAdapter Data = new OleDbDataAdapter("SELECT * FROM Articulos", Conn);
DataSet DSet = new DataSet();
Conn.Open();
Data.Fill(DSet);
Conn.Close();
_Articulos = DSet.Tables["Articulos"];
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
The try/catch is there because my VStudio 2010 installation isnt quite capable of detecting COM Exceptions somehow (Had the same issue creating the database with ADOX, the exception was uncaught, the code kept on running responsively somehow, but the DB was never written to the disk).
The DB already has the "Articulos" table, and i manually inserted some records there, but if i foreach the DataSet, i only get a Table named "Table". This is getting frustrating now :(
DSet.Tables[0].Rows is what you want.
This is what I mean.
_Articulos = DSet.Tables[0];
With that, _Articulos.Rows should be populated with the records in your database.
When several fields in a MSAccess table need to be updated (For instance Salary=Salary*Factor, SomeNumber=GetMyBusinessRuleOn(SomeNumber) etc...),and the update should affect every record in a table, which technique would you use?
I have just started to implement this with DataSets, but got stuck (Updating and persisting dataset problem)
But maybe this isn't even the ideal way to handle this kind of batch update?
Note : the updates don't have to be on disconnected data first, so a dataset is not necessary.
UPDATE :
One command won't do, I need some kind of recordset or cursor to cycle through the records
I would just use a ODBCConnection/ODBCCommand and use a SQL Update query.
There is a JET Database driver that you should be able to use to establish a database connection to a MSAccess database using the ODBCConeection object.
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\\PathTo\\Your_Database_Name.mdb; User Id=admin; Password=";
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
// Suppose you wanted to update the Salary column in a table
// called Employees
string sqlQuery = "UPDATE Employees SET Salary = Salary * Factor";
OdbcCommand command = new OdbcCommand(sqlQuery, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
You could use these websites to help you generate a connection string:
http://www.connectionstrings.com/
http://www.sqlstrings.com/
EDIT - Example for using a data reader to cycle through records in order to aply the business rule
I should note that the following example could be improved in certain ways (especially if the database driver supports parameterized queries). I only wanted to give a relatively simple example to illustrate the concept.
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
int someNumber;
int employeeID;
OdbcDataReader dr = null;
OdbcCommand selCmd = new OdbcCommand("SELECT EmployeeID, SomeNumber FROM Employees", connection);
OdbcCommand updateCmd = new OdbcCommand("", connection);
try
{
connection.Open();
dr = selCmd.ExecuteReader();
while(dr.Read())
{
employeeID = (int)dr[0];
someNumber = (int)dr[1];
updateCmd.CommandText = "UPDATE Employees SET SomeNumber= " + GetBusinessRule(someNumber) + " WHERE employeeID = " + employeeID;
updateCmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Don't forget to close the reader when we're done
if(dr != null)
dr.Close();
}
// The connection is automatically closed when the
// code exits the using block.
}
Sounds like you just need an update statement:
http://msdn.microsoft.com/en-us/library/bb221186.aspx
You can use the OleDb Provider for this.