Not able to insert update delete - asp.net

I'm using Asp.net c# and MYSql as back-end. I'm updating a table,but table is not updating.There are only 3 columns in the table.
There is no exception when I'm executing the command object. But this returns 0 value from cmd.ExecuteNonQuery().
I debugged this and found cmd.Parameters are full with values. and if i manually run the update command in mysql it works fine.
the table is as follow
column -- Datatype
ShortText -- varchar
title -- varchar
id -- int
Please guide me...
int retVal = 0;
string shortText = ((TextBox)fmvwShortText.FindControl("txtShortText")).Text.Trim();
try
{
int id = Convert.ToInt32(((Label)fmvwShortText.FindControl("lblShrtTextID")).Text);
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conn"]);
cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE temp_posts SET ShortText=#shrtText WHERE id=#id AND Title=#title";
cmd.Parameters.Add("#shrtText", MySqlDbType.VarChar).Value = shortText;
cmd.Parameters.Add("#title", MySqlDbType.VarChar).Value =Session["EditTitle"].ToString();
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = id;
con.Open();
retVal = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e) { }
return retVal;

Is it possibly a casing issue with your Title parameter? I notice you are only updating if the ID & Title match exactly?
Also as a general rule of thumb, when using objects which implement IDisposable you should wrap them with a using statement, this will make sure your objects are always disposed (even on the result of an error)
using (var con = new MySqlConnection(...))
{
using (var cmd = new MySqlCommand(...))
{
....
}
}

First of all thank you every one who kept looking and tried their best to sort out this problem with me..
Finally got the solution.
In my code I used # in cmd.CommandText and in parameters.
But when I replace this # with ? both in cmd.CommandText and in parameters and used the cmd.ExecuteScalar(); this worked.
Actually Parameter names depend on the provider. When using the provider for
SQL Server, it should start with # (e.g. #param1). For Oracle
provider, it should start with a colon (...for e.g. aram1. For
OleDb provider, just a question mark (?) would work
Thank you everyone to contribute your best... many thanks
But i'm still left with a question that ExecuteScalar() is updating the records in the database? I am with no answer... looking for this.

Try this nt sure about code formating coz currently am not using ide frmwrk
int retVal = 0;
string shortText = ((TextBox)fmvwShortText.FindControl("txtShortText")).Text.Trim();
try
{
int id = Convert.ToInt32(((Label)fmvwShortText.FindControl("lblShrtTextID")).Text);
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conn"]);
cmd = new MySqlCommand("UPDATE temp_posts SET ShortText='"+shortText+"' WHERE id='"+id+"' AND Title='"+Session["EditTitle"].ToString()+"'",con);
con.Open();
retVal = cmd.ExecuteNonQuery();
con.Close();
return retVal;
}
catch (Exception e) { }

Related

Exception | must declare scalar variable #IdAlbum

I am getting an error "must declare scalar variable #IdAlbum". I have already been through similar posts on this topic but it does not help. Can someone have a look at the code below? When i use command paramters it gives me error. If I do not use command parameters, it works fine. I have put comments in the code to highlight where the problem is.
public DataSet databind ()
{
DataSet ds = new DataSet();
string con_str = ConfigurationManager.ConnectionStrings["con_nc"].ConnectionString;
SqlConnection con = new SqlConnection(con_str);
try
{
con.Open();
string albumId = Request.QueryString["AlbumId"].Trim();
this.albumName = Request.QueryString["AlbumName"];
//getting the count of the pictures from DB and assigning it to pagesize so that all pictures of single album come in 1 page only.
string photoCountQuery = "select count(*) from gallery_photos where AlbumId=#albumId"; // THIS WORKS FINE
SqlCommand picCount = new SqlCommand(photoCountQuery, con);// THIS WORKS FINE
picCount.Parameters.AddWithValue("#albumID", albumId);// THIS WORKS FINE
int photoCount = Convert.ToInt16(picCount.ExecuteScalar());// THIS WORKS FINE
int start = (int)ViewState["start"];// THIS WORKS FINE
ViewState["pagesize"] = photoCount;// THIS WORKS FINE
//string query = "select * from gallery_photos where AlbumId='" + albumId + "'"; //// THIS WORKS FINE
string query = "select * from gallery_photos where AlbumId=#IdAlbum";// THIS is the problem. It does not work when i use command paramters
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#IdAlbum", albumId);
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds, start, (int)(ViewState["pagesize"]), "gallery_photos");
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "Exception in " + Path.GetFileName(Page.AppRelativeVirtualPath).ToString());
Context.ApplicationInstance.CompleteRequest();
}
finally
{
con.Close();
}
return ds;
}
Look at this: https://msdn.microsoft.com/en-us/library/ebxy9a8b(v=vs.80).aspx
You are doing it wrong, you should use DataAdapter to fill missing parameters.
Look also at this question and answer, it provides good explanation: c# Using Parameters.AddWithValue in SqlDataAdapter

How to use SqlConnection InfoMessage

I have this method that calls a stored procedure. My problem is that it does not return a row, but it prints a message. I am trying to capture that print message into a variable. My problem is I have never ever used InfoMessage before and I checked it out online and for the life of me I can't seem to understand it. Can someone help me out or point me in the right direction?
Here is my code:
public List<showWhatClass> showWhatMethod(string deviceWhat, int tagWhat, Decimal latit, Decimal longit, int Process, string CallNext, int CallNextVar)
{
showWhatCell = new List<showWhatClass>();
try
{
using (connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("iosShowWhat", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#DeviceId", deviceWhat);
command.Parameters.AddWithValue("#TagId", tagWhat);
command.Parameters.AddWithValue("#Latitude", latit);
command.Parameters.AddWithValue("#Longitude", longit);
command.Parameters.AddWithValue("#Process", Process);
command.Parameters.AddWithValue("#CallNext", CallNext);
command.Parameters.AddWithValue("#CallNextVar", CallNextVar);
connection.Open();
/*SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
showWhatClass item = new showWhatClass();
item.CallNext = reader.GetValue(0).ToString();
item.CallNextVar = (int)reader.GetValue(1);
showWhatCell.Add(item);
}*/
}
}
}
finally
{
connection.Close();
}
return showWhatCell;
}
I have tried the following:
connection.Open();
connection.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e)
{
showWhatClass item = new showWhatClass();
item.CallNext += "\n" + e.Message;
showWhatCell.Add(item);
};
returns nothing.
You can use an output parameter to get the message from stored procedure and use it in your code.
Add output parameter in stored procedure
#name varchar(20) output
And then set value of this parameter
set #name='Mairaj Ahmad Minhas'
Now in your code when you call stored procedure add another parameter like this
command.Parameters.Add("#name", SqlDbType.VarChar, 20);
command.Parameters["#name"].Direction = ParameterDirection.Output;
And after you have called the stored procedure do this to get value from this parameter.
string name = command.Parameters["#name"].Value.ToString();

For Tuncating table what statement is used?

I have created one sp that tuncate table.Table name is dynamic.Here I used dynamic sql.Sp is working fine.I want to execute that sp from C#.net(from cs file).
I know executenonquery returns no of row affected.executenonquery is used for insert,update and delete command.Exectesclare is used for select which has only one cell.EceuteReader is used for selecting multiple record.What shall i use that tell my tuncate table clause executed properly or not?
You can use ExecuteNonQuery to truncate the table.
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = "TRUNCATE TABLE myTable";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.ExecuteNonQuery();
lblStatus.Text = "Table Deleted Successfully.";
}
}
}
catch(Exception ex)
{
lblStatus.Text = "Table can not be deleted, Error " + ex.Message;
}
I suppose the best way is to use ExecuteNonQuery.
1. It returs the number of rows affected by the statement.
2. And if something doesn't work properly, you will get a nice SqlException which won't go by unnoticed.
try
{
procedure.ExecuteNonQuery();
nextStep.ExecuteWhatever();
}
catch(SqlException e)
{
Console.WriteLine("Oh noes!");
}

My update query doesn't work on database

I wrote this code in my login page. My code doesn't any error but update query doesn't apply on my database.
Fist query works and I redirect to index.aspx but update query (second query) doesn't apply!!!!
protected void btnLogin_Click(object sender, EventArgs e)
{
Database db1 = new Database();
string query = "select * from Admins where UserName=#username and cast(Password as varbinary)=cast(#password as varbinary)";
SqlCommand smd = new SqlCommand(query, db1.sc);
smd.Parameters.AddWithValue("#username", txtUsername.Text);
smd.Parameters.AddWithValue("#password", General.CreatePasswordHash(txtPassword.Text));
SqlDataReader sdr = smd.ExecuteReader();
smd.Parameters.Clear();
if (sdr.Read())
{
Session.Add("username", sdr[0].ToString());
string nowEnter = sdr[5].ToString();
query = "update Admins set LastEnter=#lastEnter, NowEnter=#nowEnter where UserName=#username";
string now = General.getPersianDateNow() + " ساعت " + General.getPersianTimeNow();
smd.CommandText = query;
smd.Parameters.AddWithValue("#lastEnter", nowEnter);
smd.Parameters.AddWithValue("#nowEnter", now);
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
sdr.Close();
smd.ExecuteNonQuery();
Response.Redirect("~/admin/Index.aspx", false);
}
else
{
lblError.Visible = true;
}
}
In my opinion the problem is with index of sdr. First one you invoke
Session.Add("username", sdr[0].ToString());
Two lines below you use
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
Anyway the safest way is to create select statement with named colums instead of using *
Check that the value you are using for the username exists in the table.
You're also adding the same parameter twice. I don't know how the SqlCommand class will handle that and I can't test it right now, but I think it might be a good idea to clear your parameters (smd.Parameters.Clear()) between executions.

Asp.Net select in Sql

This is going to be very simple I know. I have seen so many different ways of using sql in asp.net with no real standard. What I want to know is how to cleanly select from an sql database in asp.net and retrieve multiple records. For example: select all userids.
String sql =
"SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"]
.ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
/*
This is where I need to know how to retrieve the information from the
above command(comm). I am looking for something similiar to php's
mysql_result. I want to access the records kind of like an array or some
other form of retrieving all the data.
Also when the new SqlCommand is called...does that actual run the
SELECT STATEMENT or is there another step.
*/
conn.Close();
I think that this is what you are looking for.
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader nwReader = comm.ExecuteReader();
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
conn.Close();
I do have to say, though, that the overall approach can use a lot of tuning. First, you could at least start by simplifying access to your ConnectionString. For example, you could add the following to your Global.asax.cs file:
using System;
using System.Configuration;
public partial class Global : HttpApplication
{
public static string ConnectionString;
void Application_Start(object sender, EventArgs e)
{
ConnectionString = ConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
}
...
}
Now, throughout your code, just access it using:
SqlConnection conn = new SqlConnection(Global.ConnectionString);
Better yet, create a class in which the "plumbing" is hidden. To run the same query in my code, I'd just enter:
using (BSDIQuery qry = new BSDIQuery())
{
SqlDataReader nwReader = qry.Command("SELECT...").ReturnReader();
// If I needed to add a parameter I'd add it above as well: .ParamVal("CurrentUser")
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
}
This is just an example using my DAL. However, notice that there is no connection string, no command or connection objects being created or managed, just a "BSDIQuery" (which does lots of different things in addition to that shown). Your approach would differ depending on the tasks that you do most often.
Most of the time, I use this (note that I am also using a connection pooling approach):
public DataTable ExecuteQueryTable(string query)
{
return ExecuteQueryTable(query, null);
}
public DataTable ExecuteQueryTable(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
DataTable tbl = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(tbl);
}
return tbl;
}
}
}
Here's an adaption of your existing code:
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE [UserId] != #CurrentUserId";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
DataTable result = new DataTable();
using (var conn = new SqlConnection(strCon))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = CurrentUserID;
conn.Open();
result.Load(cmd.ExecuteReader());
}
Creating a SqlCommand doesn't execute it at all.
The command will be executed when you call ExecuteReader or something similar.
If you want something which will fetch all the results into memory, you should be looking at DataSet/DataTable. There's a tutorial for them here - or there are plenty of others on the net, and any decent ADO.NET book will cover them too.
If you don't want to fetch them all into memory at once, then ExecuteReader it the method for you. That will return a SqlDataReader which is like a database cursor - it reads a row at a time, and you ask for individual columns as you want them, calling Read to get to the next row each time.
Whereas in PHP you'd do something like,
while ($row = mysql_fetch_array ($result))
{
//this assumes you're doing something with foo in loop
$foo = $row["userid"];
//using $foo somehow
}
in .NET, you do something different. Believe me, originating from a PHP background, the transition from PHP to .NET is not easy. There's a lot of things that will seem bizarre. After a while though, it will make sense! Just stick it out. I personally like it better.
Ok.. assuming you have a DataSet like you say, you can do something like this,
//assuming you have a DataSet called myDataSet
for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
{
//likewise assuming here you're doing something with foo in loop
string foo = myDataSet.Tables[0].Rows[i]["userid"].ToString();
//similarly do something with foo in loop
}
That does the same thing as the PHP snippet.

Resources