Assign a default value for every coming int in the method - c#

i have two methods having
getlisting(string url,int ID)
i want to pass this ID to another method in another class,
class cc=new class();
cc.updatevalue(ID);
now i want to pass this int value to that updatevalue method and assign it a 0 value. and every time getlisting having different ID and passing it to update method. i have tried if else condition as well. so my question is can anyone help me in assigning that default 0 value to every coming int value.
after assigning i want to update that in my DataTable
SqlCommand cmd = new SqlCommand("UPDATE Paging SET Status='1' WHERE ID ='ID'", obj.openConnection());
and ID is throwing an error of cannot convert varchar into data type, tell me the condition with which i can give default value to every int and makes it equal to ID. thanks

I suspect the problem is with your SQL, also I suggest using parameterized query , so your code should be...
SqlCommand cmd = new SqlCommand("UPDATE Paging SET Status=#status WHERE ID =#id", obj.openConnection());
cmd.Parameters.Add("#status", SqlDbType.Int).Value = 1; // modify this to varchar if status is string
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
On the side note, we could specify default value for parameters take a look at Named and Optional Arguments.

SqlCommand cmd = new SqlCommand("UPDATE Paging SET Status='1' WHERE ID ='" . ID . "'", obj.openConnection());
You were passing ID as the string 'ID' instead of your variable.

Related

Can't update MS Access database in C#?

My code:
OleDbCommand cmd1 = new OleDbCommand("UPDATE student_info SET fee_due = #fee_due WHERE adm_no = #adm_no", con);
cmd1.Parameters.AddWithValue("#adm_no", adm_no);
cmd1.Parameters.AddWithValue("#fee_due", fee_due);
int affect = cmd1.ExecuteNonQuery();
MessageBox.Show(affect.ToString());
My code always shows 0 row affected every time but in my database the are must be a row that will be affect
Can you suggest me how I debug this problem?
Since OleDB for MS Access doesn't support named parameters (only positional parameters), you must be very careful about providing the values in the same order in which you define the parameters.
In your case, the statement lists #fee_due first, before #adm_no - but you provide the values in the other order.
Change your code like this:
OleDbCommand cmd1 = new OleDbCommand("UPDATE student_info SET fee_due = #fee_due WHERE adm_no = #adm_no", con);
// provide the value for #fee_due FIRST
cmd1.Parameters.AddWithValue("#fee_due", fee_due);
// provide the value for #adm_no only after #fee_due
cmd1.Parameters.AddWithValue("#adm_no", adm_no);
int affect = cmd1.ExecuteNonQuery();
MessageBox.Show(affect.ToString());

Insert a value in a table from another table using a variable in C# , SQL Server

I have to insert some values in a table while fetching them from another table. Here is my code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string Name = rdr["Name"].ToString();
}
}
My question is how to insert the name into another table.
I do not want to use a textbox for this the value must be inserted as a variable into other table. I use following script to insert data . but error message is Id not found. Please let me know if I am missing something
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES (#string)", con);
I use following script to insert data . but error message is Id not found.
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES
(#string)", con);
You need to specify a value for all columns in the table, unless some columns have default values. Its hard to tell without the exact error message, but it sounds like Id is probably the primary key column and not set to auto increment, so you must supply a value for Id. Since you are inserting, it must be a value not yet used in the table. Depending on your needs, you might want to change finalTable's ID to be auto increment.
On a side note, you are not disposing of things (like your DB connection) that implement IDisposable. The using keyword is your friend here.

C#: OleDbCommand Update query not working?

I have a database with multiple rows and columns with default value of 0. The user have to select a column by typing in the column name in a textBox and the system will automatically increment the value in the column by 1.
using (OleDbCommand cmd2 = connection.CreateCommand())
{
int i = 1;
cmd2.CommandText = "Update NormalRoom1 SET #time = #time + #b where [Appointment_Date]= #date";
// add parameters
cmd2.Parameters.AddRange(new OleDbParameter[]
{
// a is a string variable that holds a value the user chooses
new OleDbParameter("#time", a),
new OleDbParameter("#b", i),
new OleDbParameter ("#date", dateTimePicker2.Value.ToString("dd/MM/yyyy"))
});
// execute
cmd2.ExecuteNonQuery();
}
Only values can be variables. Your #time would be a column name and that cannot be a variable. As much as I hate to say this: you will need to insert that part by text-format.
Please be extra careful when doing so, it's an attack vector for sql injection. Best scenario is you let the user pick from a combobox and then check his selection against an internal list again.

Add more parameters then are used in the query?

Is there a way to add a parameter to my SqlCommand in a way that the engine will not complain if it's not used in my query?
I have about 50 parameters to include in my query but which parameters need to be included depends highly on the situation. I could easily delete 200 lines of code if i could just put them all on top and build my query after adding my params.
A very simple / dumb / wrong.. example (yes, the solution here is to add id to the else clause)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("#name", SqlDbType.nVarChar, 250).Value = name;
if(id == null) cmd.CommandText = "INSERT INTO tab (name) VALUES (#name)";
else cmd.CommandText = "UPDATE tab SET name = #name WHERE id = #id";
This returns the error:
System.Data.SqlClient.SqlException: The parameterized query '(#id,#name) ' expects the parameter '#id', which was not supplied
If it's not possible, a simple 'No' will suffice to be accepted as an answer..
Is there a way to add a parameter to my SqlCommand in a way that the engine will not complain if it's not used in my query?
ADO.NET does not complain if you add a parameter and do not use it. The error message you report is because you are trying to use a parameter that you didn't add - the opposite scenario. Most likely, id is null. Parameters with a value of null are not added - you need to use DBNull.Value:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ((object)id) ?? DBNull.Value;
cmd.Parameters.Add("#name", SqlDbType.nVarChar, 250)
.Value = ((object)name) ?? DBNull.Value;
Alternatively, tools like "dapper" will make this easy:
conn.Execute(sql, new { id, name }); // job done

SQL Server Count Using C# Prepared Statement

Im trying to do a COUNT using C# 'Prepared Statements' but I get error: :
SqlCommand.Prepare method requires all variable length parameters to
have an explicitly set non-zero Size
Below is my code:
public int PreparedCheck(String email)
{
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("SELECT COUNT(*) FROM [dbo].[AspNetUsers] WHERE Email=#val1", conn);
cmd.Parameters.Add("#val1", SqlDbType.VarChar);
cmd.Prepare();
Int32 count = (Int32) cmd.ExecuteScalar();
return count;
}
Looks like you didn't specify your parameter value.
cmd.Parameters.Add("#val1", SqlDbType.VarChar).Value = email;
I write email as a value because you pass it as a parameter to your PreparedCheck method but you never use it.
Two errors. You don't set the value for the parameter, but you also don't set the size of the parameter as required by the Prepare method
SqlParameter p1 = cmd.Parameters.Add("#val1", SqlDbType.VarChar);
p1.Value = email;
p1.Size = 255; // This should be the size of the column EMail on the datatable
cmd.Prepare();
Simply setting the value of the parameter seems not to be enough for the Prepare method.
While the property size is changed to the string length passed as value, the error is still there and doesn't go away until you explicitly set the Size property to valid value.
This is from the REMARKS section on SqlCommand.Prepare
Before you call Prepare, specify the data type of each parameter in
the statement to be prepared. For each parameter that has a variable
length data type, you must set the Size property to the maximum size
needed. Prepare returns an error if these conditions are not met.
You need to set the value for your parameter:
cmd.Parameters.Add("#val1", SqlDbType.VarChar).Value = email;

Categories