sqlcommand for updation - sql

I have a table which I want to update using a simple update command.
protected void UpdateButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("UPDATE KPI_DETAILS_TABLE SET KPI1_Status =
#KPI1_Status, KPI2_Status = #KPI2_Status, KPI3_Status = #KPI3_Status,
KPI4_Status = #KPI4_Status, KPI5_Status = #KPI5_Status, KPI6_Status =
#KPI6_Status, Overall_Status= #Overall_Status WHERE TokenID = '" +
DropDownList1.SelectedItem.Text + "' AND TimeSet = '"
+ currentdate + "'", connection);
cmd.Parameters.AddWithValue("#KPI1_Status", DropboxKPI1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI2_Status", DropboxKPI2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI3_Status", DropboxKPI3.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI4_Status", DropboxKPI4.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI5_Status", DropboxKPI5.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI6_Status", DropboxKPI6.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Overall_Status", FinalStatus.SelectedItem.Text);
try
{
cmd.ExecuteNonQuery();
Error1.Text = "KPI Status Successfully Updated !!";
}
catch { Error1.Text = "Error during Updating status of KPIs"; }
finally { connection.Close(); }
}
However it's throwing the following exception error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The only column of datatype datetime in the database is TimeSet. But currentdate is also of data type datetime.
DateTime currentdate = DateTime.Now.ToLocalTime();
Then why is this error popping up? Please help.

a) Use parameters for the values in your WHERE clause, as well as for the SET part, and
b) Then use cmd.Parameters.AddWithValue("#TimeSet", DateTime.Now.ToLocalTime());
This will also protect you from SQL injection.
I.e. if you've got a datetime value, try to keep it as a datetime value, and don't muck about with trying to treat it as a string at any point. Let ADO.Net and SQL Server deal with any necessary conversions.

Your code should look like this:
protected void UpdateButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("UPDATE KPI_DETAILS_TABLE SET"+
"KPI1_Status = #KPI1_Status, KPI2_Status = #KPI2_Status,"+
"KPI3_Status = #KPI3_Status, KPI4_Status = #KPI4_Status,"+
"KPI5_Status = #KPI5_Status, KPI6_Status = #KPI6_Status,"+
"Overall_Status= #Overall_Status"+
"WHERE TokenID = #ID AND TimeSet = #Time", connection);
cmd.Parameters.AddWithValue("#KPI1_Status", DropboxKPI1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI2_Status", DropboxKPI2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI3_Status", DropboxKPI3.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI4_Status", DropboxKPI4.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI5_Status", DropboxKPI5.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI6_Status", DropboxKPI6.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Overall_Status", FinalStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("#ID", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Time", DateTime.Now.ToLocalTime());
try
{
cmd.ExecuteNonQuery();
Error1.Text = "KPI Status Successfully Updated !!";
}
catch { Error1.Text = "Error during Updating status of KPIs"; }
finally { connection.Close(); }
}
Repaired the mess in the string of your SqlCommand object.
Instead of adding local variables to your SqlCommand I added new SqlParameters and defined where they'd get their values from (#ID, #Time).

Instead you use DateTime.Now.ToString(); for giving the Currentdate and try again.

Related

Can't use retrieved data from one query into another one?

I need to use a variable (edifcodigo) which assigned value is retrieved from one query to insert it in a table by using other query but there is a error that says this variable is not available in actual context. I'm kind of new in aspnet, could anybody know how to figure this out?
This is the code I have:
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
string edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
That's because you declared the variable inside a different code block. Every time you open a curly bracket, you open a new code block. Every time you close the curly bracket, you close the current code block. Each code block have it's own scope - it can access variables declared in the surrounding code block, but not variables declared in "sibling" code blocks.
Also, please read about parameterized queries and how they protect you from SQL injection, and change your queries accordingly.
Also, you don't need to close the connection between the two commands, and you can reuse a single command instance in this case. Here is an improved version of your code:
//Connect to db
var connetionString = #"myconexionstring";
var sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto = #nombre_proyecto";
//find building code by querying the database
try
{
using (var conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (var cmd = new SqlCommand(sql, conexion))
{
cmd.Parameters.Add("#nombre_proyecto", SqlDbType.NVarChar).Value = uedif;
var edifcodigo = cmd.ExecuteScalar();
//Save referer friend
cmd.Parameters.Clear();
cmd.CommandText = "DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
You are declaring the string variable inside your while loop, it loses scope once you exit the while loop, move it's declaration above with:
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo = "";
You are trying to use a variable that declared in another scope. edifcodigo should be declared in the parent scope of both try blocks.
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo=""; // YOU SHOULD DECLARE edifcodigo HERE
and than rest of code will come
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referrer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Select and Update accdb database in ASP.net

I am able to select information from my database and retrieve information, but why cant i use the same to update the database?
Commandstring is what i use to write my SQL Sentences.
Not Working:
DatabaseConnection.Commandstring = ("UPDATE tbl_login SET Time='"+Settings.UpdateRecord+"' WHERE Username='"+Settings.LoginName+"' ");
Connection code:
public static string ConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + System.Web.HttpContext.Current.Server.MapPath("MainData.accdb") + "'; Persist Security Info = False;";
public static string Commandstring;
public static object result;
public static void Connect() {
using (OleDbConnection con = new OleDbConnection(DatabaseConnection.ConString)) {
con.Open();
Debug.WriteLine("Connection to DB Established");
using (OleDbCommand cmd = new OleDbCommand(Commandstring, con)) {
try {
cmd.ExecuteNonQuery();
con.Close();
Debug.WriteLine("Connection to DB Terminated");
}
catch (Exception ex) {
Debug.WriteLine("Error Updating Database: " +ex.Message);
con.Close();
}
}
}
}
}
my exception message is saying there is an Syntax error in my Update statement.
Sending the statement to Debug writeline i get:
UPDATE tbl_login SET Time='21' WHERE Username='Bob'
Time is a reserved word. Enclose it in square brackets like this:
UPDATE tbl_login SET [Time]='21' WHERE Username='Bob'
I also think you should switch to a parameter query. But the reserved word issue is the cause of your immediate problem, and will also be an issue in a parameter query.

Is there any replacement of Top in Sql dependency in signalr?

Can you please let me know how can i use Top or other sql statement in sql dependency to get Top 5 records, whenever i use this Top its always shows Sql NotificationType Subscribe.
Please help me out to get top records using query in SignalR
When i tried this its is working fine
public void SendStocksNotifications(string symbol="")
{
string conStr = ConfigurationManager.AppSettings["myConnectionString"].ToString();
using (var connection = new System.Data.SqlClient.SqlConnection(conStr))//"data source="";initial catalog="";persist security info=True;user id="";password="";multipleactiveresultsets=True;application name=EntityFramework""))
{
string newdate = DateTime.Now.ToString( "MM/dd/yyyy" );
string query = "SELECT TOP 1 [Close],Pre_Close, Volume, Pre_Volume, PercentageChange, Pre_PercentageChange, NetChange, Pre_NetChange, High, Low, Pre_High, Pre_Low,Previous, Pre_Previous, [52WH], [52WL] FROM [dbo].[History] WHERE Symbol='" + symbol + "' ORDER BY UpdatyedDate DESC";
connection.Open();
using ( SqlCommand command = new SqlCommand( query, connection ) )
{
}
}
}
But this code
private void dependency_OnChange1(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
string symbol = Vsymbol;
NotificationStocks nHub = new NotificationStocks();
nHub.SendStocksNotifications( symbol );
}
}
shows e.Type=SqlNotificationType.Subscribe.

Retrieve SQL Statement Does Not Go Into While Loop

I am having problem when doing retrieve function in 3-tier in C#. Here is the codes:
public DistributionStandardPackingUnits getSPUDetail(string distributionID)
{
DistributionStandardPackingUnits SPUFound = new DistributionStandardPackingUnits();
using (var connection = new SqlConnection(FoodBankDB.connectionString))
{
SqlCommand command = new SqlCommand("SELECT name, description, quantity FROM dbo.DistributionStandardPackingUnits WHERE distribution = '" + distributionID + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
string name = dr["name"].ToString();
string description = dr["description"].ToString();
string quantity = dr["quantity"].ToString();
SPUFound = new DistributionStandardPackingUnits(name, description, quantity);
}
}
}
return SPUFound;
}
When I run in browser, it just won't show up any retrieved data. When I run in debugging mode, I realized that when it hits the while loop, instead of executing the dr.Read(), it simply just skip the entire while loop and return null values. I wonder what problem has caused this. I tested my query using the test query, it returns me something that I wanted so I think the problem does not lies at the Sql statement.
Thanks in advance.
Edited Portion
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}

must declare variable scalar

i have this code:
private void btGuardar_Click(object sender, EventArgs e)
{
if (txDescrip.Text.Trim().Equals("") == false && txPath.Text.Trim().Equals("") == false)
{
try
{
byte[] imgData = getMyFileBytes(txPath.Text);
//Server connection
OleDbConnection connection = new OleDbConnection(strcx);
String q = "INSERT INTO MisImagenes (Id,CustomImage) values(#MyPath, #ImageData)";
//Initialize sql command object for insert
OleDbCommand command = new OleDbCommand(q, connection);
//We are passing original image path and image byte data as sql parameters
OleDbParameter pMyPath = new OleDbParameter("#MyPath", (object)txPath.Text);
OleDbParameter pImgData = new OleDbParameter("#ImageData", (object)imgData);
command.Parameters.Add(pMyPath);
command.Parameters.Add(pImgData);
//Open connection and execute insert query
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Mensaje.aviso("Imagen Guardada :)");
//Limpiamos
clearAlta();
}
catch (Exception exc)
{
Mensaje.aviso("Something went wrong! :( " + exc.Message);
}
}
}
when i execute this says "Must declare the scalar variable "#MyPath"." ... any help? please, thank you.
I'm just trying to save an image to my sqlserver db by selecting the path and id description for the image. and i just get this frustrating error
you should use '?' instead of parameter names in oledb queries
INSERT INTO MisImagenes (Id,CustomImage) values(?, ?)
similar question and answer: OleDbCommand parameters order and priority