I am running an sql database for movies and I am working on this function so that whenever a user checks out a movie, the movie would be updated saying it has been checked out, then the checked out movie would be added to a table for checked out movies. I have a code that runs without any errors but my checked out movie does not get added to my checked out table. Code for the gridview that displays the selected movie below:
<asp:ListBox ID="CheckOutList" runat="server" OnSelectedIndexChanged="Get_data" AutoPostBack="true">
</asp:ListBox>
<asp:Panel ID="panel5" runat="server" Visible="false">
<asp:GridView id="one_data" AutoGenerateColumns="false" runat="server" DataKeyNames="MovieID">
<Columns>
<asp:BoundField DataField="MovieID"
HeaderText="Movie ID"/>
<asp:BoundField DataField="MovieTitle"
HeaderText="Movie"/>
<asp:BoundField DataField="DateChecked"
HeaderText="Date Checked"/>
<asp:BoundField DataField="CheckedOut"
HeaderText="Checked Out"/>
</Columns>
</asp:GridView>
<asp:Button runat="server" Text="Choose another Movie" OnClick="GoBack" />
<asp:Button runat="server" Text="Check Out" OnClick="CheckOut" />
</asp:Panel>
CS code for checking out the movie:
public void CheckOut(object sender, EventArgs e)
{
get_connection();
try
{
connection.Open();
command = new SqlCommand("UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID", connection);
command.Parameters.AddWithValue("#DateChecked", DateTime.Now);
command.Parameters.AddWithValue("#CheckedOut", 'Y');
//command.Parameters.AddWithValue("#MovieID",);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
reader = command.ExecuteReader();
one_data.DataSource = reader;
one_data.DataBind();
reader.Close();
command = new SqlCommand("INSERT INTO checkout (MovieID, SubscriberID) VALUES #MovieID, #SubscriberID", connection);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
command.Parameters.AddWithValue("#SubscriberID", loginName.Text);
command.ExecuteNonQuery();
}
catch (Exception err)
{
// Handle an error by displaying the information.
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
connection.Close();
lblInfo.Text = "Movie Checked Out";
}
}
The UPDATE SQL statement does work saying the movie has been taken but the movie does not get added to the checked out table.
I see some missing concept.
why update use command.ExecuteReader(); while insert use command.ExecuteNonQuery(); .
I think you should use
ExecuteNonQuery
INSERT INTO checkout (MovieID, SubscriberID) VALUES #MovieID, #SubscriberID .
This sql syntax need bracket for values :
INSERT INTO checkout (MovieID, SubscriberID) VALUES (#MovieID, #SubscriberID)
I hope this solve yours.
I think you better execute coding in the transaction block. also you can update as following examlpe with ";"
connection.ConnectionString = connectionString;
command.CommandText = #"
UPDATE MultiStatementTest SET somevalue = somevalue + 1;
UPDATE MultiStatementTest SET" + (generateError ? "WONTWORK" : "") +
" somevalue = somevalue + 2;";
command.CommandType = System.Data.CommandType.Text;
command.Connection = connection;
Can I execute multiple SQL statements?
Of course you can! You can execute it in a single or multiple SqlCommand. :)
The UPDATE SQL statement does work saying the movie has been taken but
the movie does not get added to the checked out table
Are you using a local database? If yes, check out Data not saving permanently to SQL table.
Anyway, I would like to my code for data access which could help you in your development.
Disclaimer: I know that using SqlCommand as parameter is better but I got lazy so here's the string version.
public interface IDAL
{
void BeginTransaction();
void EndTransaction();
void SaveChanges();
DataTable RetrieveData(string query, [CallerMemberName] string callerMemberName = "");
string RetrieveString(string query, [CallerMemberName] string callerMemberName = "");
bool ExecuteNonQuery(string query, [CallerMemberName] string callerMemberName = "");
bool ExecuteNonQuery(string query, object[] parameters, [CallerMemberName] string callerMemberName = "");
}
public class MSSQLDAL : IDAL, IDisposable
{
private bool disposed = false;
private string _connectionString { get; set; }
private SqlTransaction _transaction { get; set; }
private SqlConnection _connection { get; set; }
private IsolationLevel _isolationLevel { get; set; }
private bool _isCommitted { get; set; }
public string ConnectionString
{
get { return _connectionString; }
}
public MSSQLDAL(string connectionString)
{
this.connectionString = _connectionString;
this._connection = new SqlConnection();
this._connection.ConnectionString = this._connectionString;
this._isolationLevel = IsolationLevel.ReadCommitted;
this._isCommitted = false;
}
public void BeginTransaction()
{
this.Open();
}
public void EndTransaction()
{
this.Close();
}
public void SaveChanges()
{
if(_transaction != null)
{
_transaction.Commit();
this._isCommitted = true;
}
this.EndTransaction();
}
public DataTable RetrieveData(string query, [CallerMemberName] string callerMemberName = "")
{
DataTable dataTable = new DataTable();
try
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = _connection;
command.Transaction = _transaction;
command.CommandText = query;
command.CommandType = CommandType.Text;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(dataTable);
}
}
//this.AuditSQL(query, string.Empty);
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
}
return dataTable;
}
public string RetrieveString(string query, [CallerMemberName] string callerMemberName = "")
{
string text = string.Empty;
try
{
using (SqlCommand oracleCommand = new SqlCommand())
{
oracleCommand.Connection = _connection;
oracleCommand.Transaction = _transaction;
oracleCommand.CommandText = query;
oracleCommand.CommandType = CommandType.Text;
using (SqlDataReader dataReader = oracleCommand.ExecuteReader())
{
dataReader.Read();
text = dataReader.GetValue(0).ToString();
}
}
//this.AuditSQL(query, string.Empty);
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
}
return text;
}
public bool ExecuteNonQuery(string query, [CallerMemberName] string callerMemberName = "")
{
bool success = false;
try
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = _connection;
command.Transaction = _transaction;
command.CommandText = query;
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
//this.AuditSQL(query, string.Empty);
success = true;
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
success = false;
}
return success;
}
public bool ExecuteNonQuery(string query, object[] parameters, [CallerMemberName] string callerMemberName = "")
{
bool success = false;
try
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = _connection;
command.Transaction = _transaction;
command.CommandText = query;
command.CommandType = CommandType.Text;
command.Parameters.AddRange(parameters);
command.ExecuteNonQuery();
}
//this.AuditSQL(query, string.Empty);
success = true;
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
success = false;
}
return success;
}
private void Open()
{
if(_connection.State == ConnectionState.Closed)
{
_connection.Open();
_transaction = _connection.BeginTransaction(_isolationLevel);
}
}
private void Close()
{
if (!this._isCommitted)
{
if (this._transaction != null)
{
this._transaction.Rollback();
}
}
if(this._connection.State == ConnectionState.Open)
{
this._connection.Close();
}
}
private void AuditSQL(string query, string message, string callerMemberName = "")
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("**************************************************************************************************");
stringBuilder.AppendLine(string.Format("DATETIME: {0}", DateTime.Now.ToString("MM/dd/yyyy HHmmss")));
stringBuilder.AppendLine(string.Format("SQL: {0}", query));
stringBuilder.AppendLine(string.Format("MESSAGE: {0}", message));
if (!string.IsNullOrWhiteSpace(callerMemberName))
{
stringBuilder.AppendLine(string.Format("METHOD: {0}", callerMemberName));
}
stringBuilder.AppendLine("**************************************************************************************************");
Logger.WriteLineSQL(stringBuilder.ToString()); // Log the query result. Add an #if DEBUG so that live version will no longer log.
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (!this._isCommitted)
{
if (this._transaction != null)
{
this._transaction.Rollback();
}
}
this._transaction.Dispose();
this._connection.Dispose();
}
// Free your own state (unmanaged objects).
// Set large fields to null.
// Free other state (managed objects).
this._transaction = null;
this._connection = null;
disposed = true;
}
}
}
Sample usage:
public void CheckOut(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; // Assuming it is in your web.config
try
{
using(MSSQLDAL dal = new MSSQLDAL(connectionString))
{
dal.BeginTransaction();
string updateQuery = "UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID";
SqlParameter uDateChecked = new SqlParameter("DateChecked", SqlDbType.DateTime);
uDateChecked = DateTime.Now;
SqlParameter uCheckedOut = new SqlParameter("CheckedOut", SqlDbType.VarChar);
uCheckedOut = 'Y';
SqlParameter uMovieID = new SqlParameter("MovieID", SqlDbType.Int);
uMovieID = CheckOutList.SelectedValue;
ICollection<SqlParameter> updateParameters = new List<SqlParameter>();
updateParameters.Add(uDateChecked);
updateParameters.Add(uCheckedOut);
updateParameters.Add(uMovieID);
bool updateSuccessful = dal.ExecuteNonQuery(updateQuery, updateParameters.ToArray());
string insertQuery = "INSERT INTO checkout (MovieID, SubscriberID) VALUES (#MovieID, #SubscriberID)";
SqlParameter iSubscriberID = new SqlParameter("SubscriberID", SqlDbType.VarChar);
iSubscriberID = loginName.Text;
SqlParameter iMovieID = new SqlParameter("MovieID", SqlDbType.Int);
iMovieID = CheckOutList.SelectedValue;
ICollection<SqlParameter> insertParameters = new List<SqlParameter>();
insertParameters.Add(iSubscriberID);
insertParameters.Add(iMovieID);
bool insertSuccessful = dal.ExecuteNonQuery(insertQuery, insertParameters.ToArray());
if(updateSuccessful && insertSuccessful)
{
dal.SaveChanges();
lblInfo.Text = "Movie Checked Out";
}
else
{
lblInfo.Text = "Something is wrong with your query!";
}
}
}
catch(Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Error reading the database.");
sb.AppendLine(ex.Message);
if(ex.InnerException != null)
sb.AppendLine(ex.InnerException.Message);
lblInfo.Text = sb.ToString();
}
}
How can I execute multiple SQL statements in a single command?
You simply need to encapsulate your queries with a BEGIN and END;.
Ex:
BEGIN
SELECT 'A';
SELECT * FROM TableA;
END;
Take note that you need to have ; after your statements. I'd use a StringBuilder to write my long queries if I were you. Also, sending multiple queries as one is only useful if you are not reading any data.
What's the IDAL interface for?
In some of my projects I had to work with different databases. Using the same interface, I am able to create a DAL class for Oracle, MSSql and MySql with very minimal code change. It is also the OOP way. :)
Please change the code like this and try.change the reader.close() after executenonquery().
try
{
connection.Open();
command = new SqlCommand("UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID", connection);
command.Parameters.AddWithValue("#DateChecked", DateTime.Now);
command.Parameters.AddWithValue("#CheckedOut", 'Y');
//command.Parameters.AddWithValue("#MovieID",);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
reader = command.ExecuteReader();
one_data.DataSource = reader;
one_data.DataBind();
command = new SqlCommand("INSERT INTO checkout (MovieID, SubscriberID) VALUES #MovieID, #SubscriberID", connection);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
command.Parameters.AddWithValue("#SubscriberID", loginName.Text);
command.ExecuteNonQuery();
reader.Close();
}
I finally found an answer after reading all the posts and found that this actually got my INSERT to work
try
{
connection.Open();
command = new SqlCommand("UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID", connection);
command.Parameters.AddWithValue("#DateChecked", DateTime.Now);
command.Parameters.AddWithValue("#CheckedOut", 'Y');
//command.Parameters.AddWithValue("#MovieID",);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
//reader = command.ExecuteReader();
command.ExecuteNonQuery();
one_data.DataSource = reader;
one_data.DataBind();
connection.Close();
connection.Open();
command = new SqlCommand("INSERT INTO checkout (MovieID, SubscriberID) VALUES (#MovieID, #SubscriberID)", connection);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
command.Parameters.AddWithValue("#SubscriberID", loginName.Text);
command.ExecuteNonQuery();
//reader.Close();
}
Related
I ask these question coz i really don't know how i'm gonna do that and is it possible to do that?
What i want is to update/change here for example STA-100418-100 in database values, update/change the 100 based on the user input, like 50 it will be STA-100418-50.
Here's the provided image to be more precise
As you can see on the image, there's a red line, if user update the quantity as 60, In Codeitem STA-100418-100 should be STA-100418-60
I really have no idea on how to do that. I hope someone would be able to help me
here's my code for updating the quantity
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.ExecuteNonQuery();
}
}
}
Here's the code to get that format in codeitems
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
Here's what I use to update SQL-Server
public static DataTable GetSqlTable(string sqlSelect)
{
string conStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(conStr);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (connection.State != ConnectionState.Open)
{
return table;
}
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
adapter.Fill(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
connection.Close();
connection.Dispose();
return table;
}
public static void GetSqlNonQuery(string sqlSelect)
{
string newObject = string.Empty;
string strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(strConn);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
cmd.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
}
Here's how to use it
DataTable dt = GetSqlTable("select Quantity from product where CodeItem = 'STA-100418-100'");
string strQuantity = dt.Rows[0]["Quantity"].ToString();
GetSqlNonQuery(string.Format("UPDATE product SET CodeItem = '{0}' WHERE = 'STA-100418-100'", strQuantity));
User will input everytime in the Quantity textbox, the textchanged event of Quantity will be hit and you will get new value everytime with the same date but with different quantity. So you can use the Code.Text to update the CodeDateTime value or you can use a global variable instead of Code.Text and use it to update the column.
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity, CodeItem = #Code where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.Parameters.Add("#Code", Code.Text);
}
}
as I understand it you need MSSQL String Functions
SELECT rtrim(left(Codeitem,charindex('-', Codeitem))) + ltrim(str(Quantity)) FROM ...
For detailed information
Using MySql, Substring the code item and then concatenate the quantity.
UPDATE Product_Details SET quantity = #quantity,CodeIem = CONCAT(SUBSTR(#code,1,11),#quantity) WHERE ProductID= #ProductID
i am creating c# project so far insert and delete buttons are working but when i hit update button it gives data has not been updated and i cant see what is wrong with my code please help
public bool Update(Classre c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
string sql = "UPDATE Class SET ClassName=#ClassName,ClassLevel=#ClassLevel WHERE ClassID=#ClassID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ClassName", c.ClassName);
cmd.Parameters.AddWithValue("#ClassLevel", c.ClassLevel);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
and this is my update button code where i call the class that holds my update code
private void button3_Click(object sender, EventArgs e)
{
c.ClassID = int.Parse(textBox1.Text);
c.ClassName = textBox2.Text;
c.ClassLevel = comboBox1.Text;
bool success = c.Update(c);
if (success == true)
{
// label4.Text = "Data Has been updated";
MessageBox.Show("Data Has been updated");
DataTable dt = c.Select();
dataGridView1.DataSource = dt;
}
else
{
//label4.Text = "Data Has not been updated";
MessageBox.Show("Data Has not been updated");
}
}
I would prefer to use a stored procedure instead of pass through sql but you could greatly simplify this. As stated above your try/catch is worse than not having one because it squelches the error.
public bool Update(Classre c)
{
USING(SqlConnection conn = new SqlConnection(myconnstring))
{
string sql = "UPDATE Class SET ClassName = #ClassName, ClassLevel = #ClassLevel WHERE ClassID = #ClassID";
USING(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#ClassName", SqlDbType.VarChar, 4000).Value = c.ClassName;
cmd.Parameters.Add("#ClassLevel", SqlDbType.Int).Value = c.ClassLevel;
cmd.Parameters.Add("#ClassID", SqlDbType.Int).Value = c.ClassID;
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows > 0;
}
}
}
I would like to find a way to exit out of datareader after the if statement so that I can execute the insert query in else statement. Is there a way to do it?
I am getting the error that dr is still open and hence cannot perform the below query.
sVendorDetails.VendorID = insertcmd.ExecuteNonQuery();
Here is the code:
public class VendorDetails
{
int _VendorID;
string _VendorName;
public int VendorID
{
set { _VendorID = value; }
get { return _VendorID; }
}
public string VendorName
{
set { _VendorName = value; }
get { return _VendorName; }
}
}
public VendorDetails VendorCheck(string sVendorName)
{
SqlCommand cmd = new SqlCommand("dbo.usp_GetVendorByVendorName", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
cmd.Parameters["#VendorName"].Value = sVendorName;
VendorDetails sVendorDetails = null;
try
{
myConnection.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
sVendorDetails = new VendorDetails();
sVendorDetails.VendorID = ((int)dr["VendorID"]);
sVendorDetails.VendorName = ((string)dr["VendorName"]).ToUpper().Trim();
}
}
else if (dr.HasRows!= true)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('VendorName:" + sVendorName + " not found. Inserting Vendor details into Vendor and Invoice table.')", true);
SqlCommand insertcmd = new SqlCommand("dbo.InsertVendorName", myConnection);
insertcmd.CommandType = CommandType.StoredProcedure;
insertcmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
insertcmd.Parameters["#VendorName"].Value = sVendorName;
sVendorDetails = new VendorDetails();
sVendorDetails.VendorID = insertcmd.ExecuteNonQuery();
sVendorDetails.VendorName = sVendorName;
}
dr.Close();
return sVendorDetails;
}
catch (SqlException err)
{
throw new ApplicationException("DB usp_GetVendorByVendorName Error: " + err.Message);
}
finally
{
myConnection.Close();
}
}
You will need to close/dispose of your DataReader prior to reusing the connection, as it's still being used.
Maybe something like this?
var readerHasRows = false;
using (var dr = cmd.ExecuteReader())
{
readerHasRows = dr.HasRows;
if(readerHasRows)
{
while (dr.Read())
{
sVendorDetails = new VendorDetails();
sVendorDetails.VendorID = ((int)dr["VendorID"]);
sVendorDetails.VendorName = ((string)dr["VendorName"]).ToUpper().Trim();
}
}
}
if(!readerHasRows)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('VendorName:" + sVendorName + " not found. Inserting Vendor details into Vendor and Invoice table.')", true);
SqlCommand insertcmd = new SqlCommand("dbo.InsertVendorName", myConnection);
insertcmd.CommandType = CommandType.StoredProcedure;
insertcmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
insertcmd.Parameters["#VendorName"].Value = sVendorName;
sVendorDetails = new VendorDetails();
VendorDetails.VendorID = insertcmd.ExecuteNonQuery();
sVendorDetails.VendorName = sVendorName;
}
There are a few things I would like to mention
Your main issue is that you are not closing your DataReader. You can use the using statement for it
You don't need to explicitly open and close the SqlConnection. The SqlCommand object will do it as needed.
You don't need to check with if (dr.HasRows) and then check again in while (dr.Read()). Also, you don't need to loop to pick up only one row of data.
Ideally, I would put the "Fetch" part in a separate function and the "insert" in a separate function, so the functions stay small and reusable.
Your pattern is superfluous if (flag) {TakeAction();} else if (!flag) {TakeAction2();}. Every time the code hits theelse, it will also hit theif (!flag)`
sVendorDetails.VendorID = insertcmd.ExecuteNonQuery(); line looks fishy. If your Stored Procedure returns the VendorId, then you should use ExecuteScalar. Currently it is just storing 1 in all case since you are presumably inserting one row.
Don't discard the original SqlException when creating a custom ApplicationException. Upstream system might want to know more details than you are passing. Pass it along as the InnerException
I have also changed some stylistic aspects:
The variable names changed to the more commonly used camelCase, instead of the incorrectly used Hungarian Notation (sVendorDetails instead of oVendorDetails)
Brace in K&R style
Used var when the right side is a new statement
Use Object Initializers instead of creation+assignment
Below is the code
public VendorDetails VendorCheck(string vendorName, SqlConnection myConnection) {
try {
return GetVendor(vendorName, myConnection) ?? InsertVendor(vendorName, myConnection);
} catch (SqlException err) {
throw new ApplicationException("DB usp_GetVendorByVendorName Error: " + err.Message, err);
}
}
VendorDetails GetVendor(string vendorName, SqlConnection myConnection) {
using (var cmd = new SqlCommand("dbo.usp_GetVendorByVendorName", myConnection)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
cmd.Parameters["#VendorName"].Value = vendorName;
using (SqlDataReader dr = cmd.ExecuteReader()) {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('VendorName:" + vendorName + " not found. Inserting Vendor details into Vendor and Invoice table.')", true); // TODO: Does this really belong here!?!?
if (dr.Read()) {
return new VendorDetails {
VendorID = ((int)dr["VendorID"]),
VendorName = ((string)dr["VendorName"]).ToUpper().Trim()
};
}
}
}
return null;
}
VendorDetails InsertVendor(string vendorName, SqlConnection myConnection) {
using (var insertcmd = new SqlCommand("dbo.InsertVendorName", myConnection)) {
insertcmd.CommandType = CommandType.StoredProcedure;
insertcmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
insertcmd.Parameters["#VendorName"].Value = vendorName;
return new VendorDetails {
VendorID = (int)insertcmd.ExecuteScalar(),
VendorName = vendorName
};
}
}
I am trying to add Sql Parameters to my project but i have the database connections in a class. How would i go about adding them as the code is trying to read employerId as a column name
I have this code in a class to read and return from a database:
public SqlDataReader ExecuteQuery(String query)
{
SqlCommand cmd = new SqlCommand(query,sqlConn);
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
and this code in a web service:
[WebMethod]
public string CheckTime1(string employerId)
{
try
{
UseDatabase useDb = new UseDatabase("database.mdf");
string queryString = "SELECT * FROM [employer] WHERE [employerId] =" + employerId;
useDb.ConnectToDatabase();
SqlDataReader dbReader = useDb.ExecuteQuery(queryString);
if (dbReader != null && dbReader.HasRows)
{
return "RECORDS EXIST";
}
else if (dbReader == null)
{
return "RECORDS DONT EXIST";
}
else
{
return "Error";
}
useDb.DisconectDatabase();
}
catch (Exception exq)
{
return exq.ToString(); ;
}
}
Although I strongly encourage you to rethink your data access layer from scratch, here is an easy solution to your problem:
public SqlDataReader ExecuteQuery(String query, params object[] p)
{
SqlCommand cmd = new SqlCommand(query, sqlConn);
for (int i = 0; i < p.Length; i++)
{
cmd.Parameters.Add(new SqlParameter("#p"+i, p[i]));
}
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
Then call it like this:
public string CheckTime1(string employerId)
{
...
string queryString = "SELECT * FROM [employer] WHERE [employerId] = #p0";
SqlDataReader dbReader = useDb.ExecuteQuery(queryString, employerId);
...
}
I have a DataClassLibrary attached to my ASP.Net project. I use it to access the database to get my values. I want to take the values given in the Line1 class and put them in the corresponding label. I tried DataLibraryClass.Line1 NewDataA = new DataLibraryClass.Line1(); but it gives me a zero I know that they have values. Could it be that my NewDataA = new is causing it to return zero? I also used breakpoints in the Line1 class and it never reaches the database query. How can I get the data I need into the labels properly?
DataLibraryClass
Line1:
var sqlString = new StringBuilder();
sqlString.Append("SELECT CaseNum6, CaseNum9, Group, Completion ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE Group = 1 OR Group = 2 ");
sqlString.Append("AND Completion = 0 ");
SqlDataReader reader = null;
SqlConnection dbConn = DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseNum6", CaseNum6 )};
try
{
reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
if (reader != null)
{
if (reader.Read())
{
CaseNum6 = (int)reader["CaseNum6"];
CaseNum9 = (int)reader["CaseNum9"];
Group = (int)reader["Group"];
Completion = (bool)reader["Completion"];
}
else
throw new Exception("No record returned");
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
DataLibraryClass
DBHelper:
private DBHelper() { }
public static SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
}
public static SqlConnection getFRESHConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["FRESHConnection"].ConnectionString);
}
public static SqlDataReader executeQuery(SqlConnection dbConn, string sqlString, SqlParameter[] parameters)
{
SqlCommand cmd = null;
SqlDataReader reader = null;
try
{
if (dbConn.State == ConnectionState.Closed)
dbConn.Open();
cmd = dbConn.CreateCommand();
cmd.CommandText = sqlString;
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
reader = cmd.ExecuteReader();
cmd.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return reader;
Code behind ASP page:
DataClassLibrary.LineAData NewDataA = new DataClassLibrary.LineAData();
DataClassLibrary.LineBData NewDataB = new DataClassLibrary.LineBData();
protected void Page_Load(object sender, EventArgs e)
{
L1.Text = NewDataA.CaseNum6.ToString();
L2.Text = NewDataA.CaseNum9.ToString();
L4.Text = NewDataB.CaseNum6.ToString();
L5.Text = NewDataB.CaseGNum9.ToString();
}
Upon setting up the webpage I failed to realize the behind code was set to .vb not .cs which is why everything was not working.