SQL Output Inserted - c#

I have two buttons on a page, one that logs a start time, and one that logs an end time.
The start time button performs an sql insert.
At that point i need to grab the primary key that's create. To do this i want to use the sql command (output inserted).
Then when the stop time is clicked,the row should be update with a stop time using the primary key from the start in the where clause.
I believe insert SQL is correct but i don't know how to pass the primary key to the next command.
Code dump, with what i have so far.
var command1 = "INSERT INTO [Time] ([Start Time], [Work Order]) OUTPUT INSERTED.PrimaryKey VALUES (#StartTime, #Work_Order)";
using (SqlConnection cnn1 = new SqlConnection(cnnString))
{
using (SqlCommand cmd1 = new SqlCommand(command1, cnn1))
{
cmd1.Parameters.AddWithValue("#StartTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd1.Parameters.AddWithValue("#Work_Order", SqlDbType.Int).Value = e.CommandArgument;
cnn1.Open();
Label1.Text = cmd1.ExecuteScalar().ToString();
cnn1.Close();
}
}
var command = "UPDATE [Time] SET [Stop Time] = #StopTime WHERE [PrimaryKey] = #PrimaryKey";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(command, cnn))
{
cmd.Parameters.AddWithValue("#StopTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd.Parameters.AddWithValue("#PrimaryKey", *PrimaryKey from INSERT output*
cnn.Open();
cmd.ExecuteNonQuery();
}
}

instead of having it go to the label have it go to an int and then set the label text with the int. Then pass the int on the second part. Declare the int outside the scope of the using statements though or it will be disposed and you will get a null reference exception when you try and call it later.
Edit: To add, this would be better if you convert to stored procs and define the SqlParameter objects (you don't have them, you'll need them).
SqlParameter
int myPK;
var command1 = "INSERT INTO [Time] ([Start Time], [Work Order]) OUTPUT INSERTED.PrimaryKey VALUES (#StartTime, #Work_Order)";
using (SqlConnection cnn1 = new SqlConnection(cnnString))
{
using (SqlCommand cmd1 = new SqlCommand(command1, cnn1))
{
cmd1.Parameters.AddWithValue("#StartTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd1.Parameters.AddWithValue("#Work_Order", SqlDbType.Int).Value = e.CommandArgument;
cnn1.Open();
myPk = Convert.ToInt32(cmd1.ExecuteScalar());
Label1.Text = myPk.ToString();
cnn1.Close();
}
}
var command = "UPDATE [Time] SET [Stop Time] = #StopTime WHERE [PrimaryKey] = #PrimaryKey";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(command, cnn))
{
cmd.Parameters.AddWithValue("#StopTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd.Parameters.AddWithValue("#PrimaryKey", myPK);
FindControl("Work_OrderLabel"); ;
cnn.Open();
cmd.ExecuteNonQuery();
}
}

Related

What function do I need to write to remove from table?

It's my function to add to a table:
public int insertHistory(string title, string description, int isDone, int userId)
{
int s = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO History(title,description,isDone,userId) VALUES(#param1,#param2,#param3,#param4)";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#param1", SqlDbType.NVarChar, 10).Value = title;
cmd.Parameters.Add("#param2", SqlDbType.NVarChar, 400).Value = description;
cmd.Parameters.Add("#param3", SqlDbType.Int).Value = isDone;
cmd.Parameters.Add("#param4", SqlDbType.Int).Value = userId;
cmd.CommandType = CommandType.Text;
s = cmd.ExecuteNonQuery();
}
}
return s;
}
What code do I need to write to remove from the table by title or something?
You have asked to delete using Title and here is how to do it
public int deleteHistory(string title)
{
int s = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "DELETE FROM History WHERE Title = #title)";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#title", SqlDbType.NVarChar, 10).Value = title;
s = cmd.ExecuteNonQuery();
}
}
return s
}
However in this way you could end to delete more records than you want. If two or more records have the same title you will delete all records with the same title. You could mitigate this problem adding also the UserID to the where condition and the relative parameter to the parameters collection.
"DELETE FROM History WHERE Title = #title AND UserID = #uid"
So you delete only titles of a specific user, but still this is not safe. If your table has an IDENTITY column and you retrieve the values from that column when you read the records then you can pass that unique value to your query and delete specifically only one record.
"DELETE FROM History WHERE HistoryID = #hid"
as you are using SqlConnection and a plain SQL statement. You need to call a Delete statement in your code:
public void DeleteHistory(string title)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "delete from History where title= #title";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#title", SqlDbType.NVarChar).Value = title;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}

Database is not updating after running stored procedure in asp app

I have an asp app that should be able to let a user update an entry in a sql server database. When I run my stored procedure though in my method, nothing happens to the database.
public void updateFeature(Feature updatedFeature)
{
using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment)))
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "usp_UpdateFeature";
sqlCommand.Parameters.AddWithValue("#FeatureName", updatedFeature.FeatureName);
sqlCommand.Parameters.AddWithValue("#FeatureID", updatedFeature.FeatureID);
sqlCommand.Parameters.AddWithValue("#FeatureDescription", updatedFeature.Description);
sqlCommand.Parameters.AddWithValue("#FieldName", updatedFeature.FieldName);
sqlCommand.Parameters.AddWithValue("#OnOffSwitch", updatedFeature.IsOn);
sqlCommand.Parameters.AddWithValue("#ChannelID", updatedFeature.ChannelID);
sqlCommand.Parameters.AddWithValue("#ProductID", updatedFeature.ProductID);
sqlConnection.Open();
int numberOfRowsChanged = sqlCommand.ExecuteNonQuery();
}
}
and my stored procedure looks like this
ALTER PROCEDURE [dbo].[usp_UpdateFeature]
(
#FeatureID int,
#FeatureName varchar(30),
#FeatureDescription varchar(200) = null,
#FieldName varchar(40),
#OnOffSwitch bit,
#ChannelID varchar(3),
#ProductID varchar(2)
)
AS
SET NOCOUNT ON
UPDATE FM_Feature
SET FeatureName = #FeatureName,
FeatureDescription = #FeatureDescription,
FieldName = #FieldName,
OnOffSwitch = #OnOffSwitch,
ProductID = #ProductID,
ChannelID = #ChannelID
WHERE FeatureID = #FeatureID
The numberOfRowsChanged parameter returns -1 but I do not get any exceptions or errors. Is there something that I am missing or not understanding?
I think that you need to open your connection before you create your command, i hope that will be helpful for you .
using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment))
sqlConnection.Open();
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "usp_UpdateFeature";
sqlCommand.Parameters.AddWithValue("#FeatureName", updatedFeature.FeatureName);
sqlCommand.Parameters.AddWithValue("#FeatureID", updatedFeature.FeatureID);
sqlCommand.Parameters.AddWithValue("#FeatureDescription", updatedFeature.Description);
sqlCommand.Parameters.AddWithValue("#FieldName", updatedFeature.FieldName);
sqlCommand.Parameters.AddWithValue("#OnOffSwitch", updatedFeature.IsOn);
sqlCommand.Parameters.AddWithValue("#ChannelID", updatedFeature.ChannelID);
sqlCommand.Parameters.AddWithValue("#ProductID", updatedFeature.ProductID);
int numberOfRowsChanged = sqlCommand.ExecuteNonQuery();
}
enjoy it .

System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'file'

i'm new to AsP.net when i'm trying my usual code to connect to database there's exception keep shown and idon't know what's wrong
the exception is :
" System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'file'."
and this my code :
string ID = Request.QueryString["id"];
SqlCommand cmd = new SqlCommand("select title,file path,Upload Date from [Media] where ID=#id", conn);
cmd.CommandType = CommandType.Text;
SqlDataReader rdr=null;
try
{
conn.Open();
rdr = cmd.ExecuteReader();
try
{
conn.Open();
rdr = cmd.ExecuteReader();
// print the CustomerID of each record
while (rdr.Read())
{
pathTextBox.Text = rdr["file Path"].ToString();
DateTextBox.Text = rdr["Upload Date"].ToString();
titleTextBox.Text = rdr["title"].ToString();
}
Image1.ImageUrl = pathTextBox.Text;
}
if you have spaces in column names you need to use brackets like below
select title,[file path],[Upload Date] from [Media] where ID=#id
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "select title,[file path],[Upload Date] from [Media] where ID=#id";
cmd.Parameters.AddWithValue("#id", idval); // set the id parameter
using (var reader = cmd.ExecuteReader())
{
if (reader.Read()) // you don't need while loop
{
pathTextBox.Text = reader.GetString(reader.GetOrdinal("[file path]"))
}
}
}
If your column names contains white space (which is not recomended) you should use square brackets like []. For example, [Upload Date]
Column names must follow the rules for identifiers.
From Database Identifiers
SELECT *
FROM [My Table] --Identifier contains a space and uses a reserved keyword.
WHERE [order] = 10 --Identifier is a reserved keyword.
That's why you should use them like;
select title,[file path],[Upload Date]
Also you don't add your parameter value anywhere in your code.
SqlCommand cmd = new SqlCommand("select title,[file path],[Upload Date] from Media where ID=#id", conn);
cmd.Parameters.AddWithValue("#id", YourIDValue);
Also use using statement to dispose your SqlConnection and SqlCommand.
using (SqlConnection conn = new SqlConnection(YourConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
//Your code..
}
}

Update SQL command C#

I'm trying to update a database from my program in C#.
Here is my code which connects to the database and the attempts to update the date column in my RoomsTable table. It looks good to me but nothing happens in the database.
updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";
updateConnection.Open();
MessageBox.Show("Connected");
string updateCommand = "UPDATE RoomsTable SET Date Checked='9/27/2012'";
updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);
updateConnection.Close();
updateConnection.Dispose();
I don't know why it isn't working. It looks to me like everything is there.
use OleDBCommand
string updateCommand = "UPDATE RoomsTable SET [Date Checked]='9/27/2012'";
updateCommand = new OleDbCommand(updateCommand, updateConnection);
updateCommand.ExecuteNonQuery();
updateConnection.Close();
maybe you could refractor the code using Using statement and parameterized the query. and column name Date Checked should be escaped with brackets.
string updateCommand = "UPDATE RoomsTable SET [Date Checked]=#checkedDate WHERE ID = #id"; // '9/27/2012'
using (OleDbConnection conn = new OleDbConnection("connectionStringHERE"))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandText = updateCommand;
comm.CommandType = CommandType.Text
comm.Parameters.AddWithValue("#checkedDate", this.dateTimePicker1.Value)
comm.Parameters.AddWithValue("#id", row.roomID);
try
{
comm.Open();
conn.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
you have to write this:
updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";
updateConnection.Open();
MessageBox.Show("Connected");
string updateCommand = "UPDATE RoomsTable SET Date Checked= '"+9/27/2012+"' ";
updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);
updateConnection.Close();
updateConnection.Dispose();

ASP.net why are these queries not executing?

In my code neither of these queries appear to be running. The debug label is printing as "end" so it is executing something inside that code block, just appears it doesn't like the queries?
// Check input is all valid
if (Page.IsValid)
{
debug.Text = "begin";
using (SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand(
"UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO tblSiteSettings (allowProductRatings, allowComments, " +
"siteName, settingDate, isActive) VALUES (#allowRatings, " +
"#allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cn.Close();
}
debug.Text = "end";
}
}
A few questions:
Why are they not executing?
In classic ASP for inserts, updates and deletes I would use con.Execute(query) as supposed to using a recordset, am I running my update statement correctly here?
Is my design of the queries good, or should I be executing them in a different manner?
The reason it's not doing anything is because you're not actually executing the queries. What you need to do is:
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblSiteSettings (allowProductRatings, allowComments, siteName, settingDate, isActive) VALUES (#allowRatings, #allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
It's the line cmd.ExecuteNoneQuery(); that you're missing. There are various different Execute methods exposed by the SqlCommand class, the most commonly used are:
ExecuteNonQuery: Executes a query and returns no result from the query (it does return the rows affected as its return value however)
ExecuteScalar: Executes a query and returns the value in the first column of the first row
ExecuteReader: Executes a query and returns the data to a SqlDataReader
Your are missing
cmd.ExecuteScalar();
You may also reuse you SqlConnection, you can open the connection right after the using (SqlConnection cn = new Sql... statement. You don't have to close the connection when the SqlConnection is in a using block, accordning to the documentation the connection is closed when you are leaving the using block.

Categories

Resources