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();
}
}
}
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 have written a code which contains a SQL query. The SQL query works fine (because I can see the effect on the database). But I want to show the message of the SQL. When we run this query on SQL server, it gives the message below and we understand the query has been executed correctly:
"The query has been executed successfully for the user xxx."
Below is the code I have written for SQL query execution which works fine but I want to be able to print the above message I mentioned.
//SQL Server Connection
string con_str_reenable = "Data Source=SQLSERVER;Initial Catalog=DATABASE;Integrated Security=True";
SqlConnection con_db_reenable = new SqlConnection(con_str_reenable);
//SQL Query:
string reenable_query="The query is pasted here(Exec **** XXX)";
SqlCommand rep_com = new SqlCommand(reenable_query, con_db_reenable);
try
{
SqlDataAdapter sda1 = new SqlDataAdapter();
sda1.SelectCommand = rep_com;
DataTable dbdataset1 = new DataTable();
sda1.Fill(dbdataset1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
Please help me be able to print the message without changing SQL access codes above.
Thanks
That's just what SSMS displays.. You can do a similar thing, eg executing a ExecuteNonQuery returns the number of Rows affected - so you could print a message "x number of records updated".
In your example with populating a DataTable you can print out "The query has been executed successfully for the user xxx" every time there isn't an exception.
Try InfoMessage event in SqlConnection
Microsoft's sample:
// Assumes that connection represents a SqlConnection object.
connection.InfoMessage += new SqlInfoMessageEventHandler(OnInfoMessage);
protected static void OnInfoMessage(object sender, SqlInfoMessageEventArgsargs) {
foreach (SqlError err in args.Errors) {
Console.WriteLine("The {0} has received a severity {1}, state {2} error number {3}\non line {4} of procedure {5} on server {6}:\n{7}",
err.Source, err.Class, err.State, err.Number, err.LineNumber, err.Procedure, err.Server, err.Message);
}
}
And of course you can use ExecuteNonQuery method which returns how many rows was processed.
From my understanding of your question, you could use string.Format
For example:
//Declare variable for storing user string
string username = "xxx"; //You can always change it later
string reenable_query= string.Format("Exec procedure_name #parameter = {0}",username); //{0} will be replaced by the username
SqlCommand rep_com = new SqlCommand(reenable_query, con_db_reenable);
try
{
SqlDataAdapter sda1 = new SqlDataAdapter();
sda1.SelectCommand = rep_com;
DataTable dbdataset1 = new DataTable();
sda1.Fill(dbdataset1);
//Show Message *Add here
string show = string.Format("The query has been executed successfully for the user {0}", username);
MessageBox.Show(show);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
But I recommend using a different method of executing your query, your current code is unprotected from SQL Injections, I suggest you do this
using (SqlConnection connect = new SqlConnection())
{
DataSet tmp = new DataSet();
connect.ConnectionString = conString;
connect.Open();
SqlDataAdapter adapter = new SqlDataAdapter(*your query*, connect);
adapter.Fill(tmp);
}
I am creating winform application that have DataGrigView to present a table.
I have a DAL class that is responsible to work with DB.
There are one method that loads data of the table:
public static void GetItemsByOrder(int orderId, ref DataSet dataSet)
{
string queryString = #"Select Id,OrderId as [מס' הזמנה],ItemCode as[מק""ט], ItemName as [שם פריט], ReceiptDate as [ת. הספקה],
WarrantyExpDate as [באחריות עד],SuppliersItemCode as [מק""ט ספק], Supplier as [ספק], Count as[כמות], Active
FROM OrdersManager_Items where OrderId = #param";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#param", orderId);
SqlDataAdapter adapter = new SqlDataAdapter(command);
try
{
lock (myLock)
{
adapter.Fill(dataSet,"Items");
}
}
catch (Exception ex)
{
LogWriter.WriteLogEntry(LogWriter.LogType.ERROR, string.Format("Failed to get Items by OrderId code from DB."+
"This is due to exception: {0},\n StackTrace: {1}. ", ex.Message, ex.StackTrace));
dataSet = null;
}
}
And second method that is responsible to update the DB with the changes that were made in the table:
public static bool UpdateItemsByOrder(int orderId, DataSet data)
{
string queryString = #"Select Id,OrderId as [מס' הזמנה],ItemCode as[מק""ט], ItemName as [שם פריט], ReceiptDate as [ת. הספקה],
WarrantyExpDate as [באחריות עד],SuppliersItemCode as [מק""ט ספק], Supplier as [ספק], Count as[כמות], Active
FROM OrdersManager_Items where OrderId = #param";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#param", orderId);
SqlDataAdapter adapter = new SqlDataAdapter(command);
try
{
lock (myLock)
{
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
int rowsUpdated = adapter.Update(data,"Items");
return true;
}
}
catch (Exception ex)
{
LogWriter.WriteLogEntry(LogWriter.LogType.ERROR, string.Format("Failed to update Items table in DB. This is due to exception: {0},\n StackTrace: {1}. ", ex.Message, ex.StackTrace));
return false;
}
}
The problem:
If in the Items table new rows were aded or deleted - UpdateItemsByOrder add/delete the rows in the DB as expected.
But updates in existing rows of the Items table does not updated in DB.
There are no error or exceptions.
I have tryed to add builder.GetUpdateCommand() command = no result.
I will be happy to get any help or advice. Thanks
P>S> I am using this MSDN LINK to learn how to work with SQLAdapter
Ok, with the advice of sallushan I got the solution:
The reason why DataAdapter doesn't updated the DB is that updated rows in DataTable has RowState value "Unchanged" instead "Modified".
There is 2 basic ways to resolve this problem:
Update the data direcrly in DataTable and not in DGV
Call DataTable.Rows[indexOfUpdatedRowInDGV].EndEdit() method, after making updates through DGV, as described Here.
Thanks to all for a help :-)
You do realize that you run a SELECT command instead of update right?
My guess is adapter.Update just does select and then reports that no lines where updated since none were.
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.
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.