Print SQL query message in C# - c#

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);
}

Related

Check if Windows user credentials have access to a SQL Server table

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).

Compare Sno and display complete infromation form SQL Server Table

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();
}
}
}

Error during insert of record from asp.net into SQL Server database

I got this error during insert of data into a SQL Server database
Here is my code in button click event
try
{
string ConnString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf;Integrated Security=True;Connect Timeout=900,providerName=System.Data.SqlClient";
SqlConnection con = new SqlConnection(#ConnString);
SqlCommand cmd = new SqlCommand("InsertBodyTypeMaster", con);
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("bodytypename", txtBTname.Text.ToString());
con.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
lblmessage.Text = "Record Inserted Succesfully into the Database";
lblmessage.ForeColor = System.Drawing.Color.CornflowerBlue;
}
con.Close();
con.Dispose();
}
catch (Exception ex)
{
lblmessage.Text = ex.ToString();
}
I see a few things wrong;
As mentioned, you need to change your Connect Timeout=900, to Connect Timeout=900;
You need to delete providerName=System.Data.SqlClient part since you already using the .NET provider for SQL Server. Provider names for .NET are implicit based on the implementing class and not needed to specified in the connection string. When you delete this, you will not need ; at the end of Connect Timeout=900; anymore
Use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
Final connection string should be as;
string ConnString = "Data Source=(LocalDB)\v11.0,AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf;Integrated Security=True;Connect Timeout=900";
You have a comma and not a semi-colon after the 900 in the connect timeout property in the connection string.
Cause your connection string is total weird. remove those ; and replace them with ,. Also, make sure you spell them properly. It should be like
string ConnString = "Data Source=(LocalDB)\v11.0,AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf,Integrated Security=True,Connect Timeout=900;providerName=System.Data.SqlClient";
Also the below line
SqlConnection con = new SqlConnection(#ConnString);
It should be
SqlConnection con = new SqlConnection(ConnString);
You are calling Dispose() inside try block which is big blunder as shown below. Either use Using(...) block (or) finally block
try
{
....
con.Close();
con.Dispose();
}
Should be
finally
{
con.Close();
con.Dispose();
}
Looks like it's time you should start reading through documentation.

SqlDataAdapter.Update(dataset) method inserts new rows but does not updates existing rows

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.

Blank values in SqlDatasource

After setting up my SqlDataSource on another page to display the values, they come up as 2 blanks for the 2 times I entered test values on the comments page.
I think I'm missing something in getting them into the table in the SQL Server database value?
I'm not sure what information is needed here, so please inform me.
Thanks in advance
EDIT #1 for user request for CODE
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("Data Source=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("Email", txtEmail.Text);
cmd.Parameters.AddWithValue("Comments", txtComment.Text);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
}
EDIT #2
The values seems to be empty for the Name, Phone, Email, and Comments in the database and when I test the query, so I think it's registering the entries, just not taking the values into the SQL?
EDIT #3
Due to a suggestion by coder and rs, I've done what they've said. And now I get this error.
"String or binary data would be truncated. The statement has been terminated."
The code has been updated as well.
EDIT #4
This question is a follow up for SQL Server Error, 'Keyword not supported 'datasource'.
Remove all the "" similar to this txtPhone.Text = ""; before entering values to SQL as Server you're entering null values to that. So even if you give some values to the textbox it takes predefined NULL values and it dosen't enter either of them.

Categories