SQLException Must declar scalar variable "#variableName" - c#

I am having some trouble trying to update database at a specific row, I am receiving the error Must declare scalar variable "#lvl". Not quite sure what I am supposed to do. Do I need to declare value within my SQL Statement?
private void button1_Click(object sender, EventArgs e)
{
GridViewCellInfo grd = (GridViewCellInfo)radGridView1.Rows[0].Cells[0];
string lvl = grd.Value.ToString();
string sqlPatientCmd =
#"UPDATE MotorTB
SET RightColumn = #RightColumnCB, LeftColumn = #leftColumnCB
WHERE (Level = #lvl)";
SqlConnection connString = new SqlConnection(#"Data Source=MERCURY\SQLEXPRESS;Initial Catalog=AsiaDB; Integrated Security=SSPI;User ID=MERCURY\Sophie;");
try {
connString.Open();
SqlCommand sqlCmdStatement = new SqlCommand(sqlPatientCmd, connString);
GridViewCellInfo grid;
grid = (GridViewCellInfo)radGridView1.Rows[0].Cells[1];
string rightColVal = grid.Value.ToString();
grid = (GridViewCellInfo)radGridView1.Rows[0].Cells[2];
string leftColVal = grid.Value.ToString();
sqlCmdStatement.Parameters.AddWithValue("#rightColumnCB", rightColVal);
sqlCmdStatement.Parameters.AddWithValue("#leftColumnCB", leftColVal);
sqlCmdStatement.ExecuteScalar();
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
// Close the connection
try {
connString.Close();
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}

You'll need to add the lvl var as SqlParamter
sqlCmdStatement.Parameters.AddWithValue("#lvl", lvl);

#lvl needs to be supplied as a parameter or otherwise defined in the query.

Related

How to update oracle database table in c# with variable from text.box

When I click on update button I dont get any errors but my table isnt updated.
private void Button3_Click(object sender, EventArgs e)
{
try
{
OracleConnection cnn = new OracleConnection(oradb);
cnn.Open();
oracleCommand = new OracleCommand("UPDATE KUPAC SET NAZIVKUPCA = :NAZIVKUPCA, PIB = :PIB, MATICNIBROJ = :MATICNIBROJ, ZIRORACUN = :ZIRORACUN, EMAIL = :EMAIL WHERE KUPACID = :KUPACID", cnn);
oracleCommand.Parameters.Add("#KUPACID", Convert.ToInt32(txtKupacId.Text));
oracleCommand.Parameters.Add("#NAZIVKUPCA", txtNazivKupca.Text);
oracleCommand.Parameters.Add("#PIB", txtPIB.Text);
oracleCommand.Parameters.Add("#MATICNIBROJ", txtJMBG.Text);
oracleCommand.Parameters.Add("#ZIRORACUN", txtZiroRacun.Text);
oracleCommand.Parameters.Add("#EMAIL", txtEmail.Text);
int result = oracleCommand.ExecuteNonQuery();
MessageBox.Show("Kupac uspesno izmenjen");
}
catch (Exception exc)
{
MessageBox.Show("Greska prilikom izmena u bazi." + exc.Message);
}
finally
{
}
OsveziKupce();
ObrisiPolja();
}
I get message "Kupac uspesno izmenjen", which means that table should be updated, but nothing happens

update statement error in image

private void btnupdate_Click(object sender, EventArgs e)
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
try
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Update not possible");
}
else
{
cnn.Open();
cmd3.CommandText = "update Slab set indi = #img1 where s_flatno = #s_flatno and s_name = #s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
cnn.Close();
}
}
In this code, I'm updating image in the position indi and I'm setting a new img1 in byte. While press update I'm getting an error
Must declare scalar variable #img1
You have named your variable #img1 in the SQL Statement, but #indi when you declared the variable.
Please note that best practice when handling DBConnection is as a local variable inside a using statement, and you better use one of the overloads of Add when adding parameters to a command instead of AddWithValue. For more information, read Can we stop using AddWithValue() already?
Here is an improved version of your code:
private void btnupdate_Click(object sender, EventArgs e)
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Updation not possible");
}
else
{
try
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
var sql = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
// I'm assuming SQL Server based on the error message
using(var cnn = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.Add("#indi", SqlDbType.VarBinary).Value = img1;
cmd.Parameters.Add("#s_flatno", SqlDbType.VarChar).Value = txtfno.Text;
cmd.Parameters.Add("#s_name", SqlDbType.VarChar).Value = txtslab.Text;
}
cnn.Open();
cmd3.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
There is a small issue with you code. You have not passed #img1 parameter. You are sending it as #indi. Either Change #img1 to #indi in sql query string or change #indi to #img1 in add parameter statement:
cnn.Open();
cmd3.CommandText = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();

Connect to database in sepaerate method of my SqlCommand

I have a form that checks whether values are in a database before adding them. Each field is in a different table, and to keep everything clean, I have a checkExists method for each field. Is there a way to have a separate method that connects to the database, so that I don't have to connect in every field method?
I'd like to do something like this so that my code is less messy:
public void SetConnection()
{
SqlConnection myConnection =
new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
}
public Boolean CheckData_Company(string[] items)
{
Class_DB set_conn = new Class_DB();
try
{
set_conn.SetConnection();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
{
return true;
}
else
{
return false;
}
}
But I get a
local variable set_conn
Argument 2: Cannot Convert from Class_DB to System.Data.SqlClient.SqlConnection
I understand the error, so what can I do to return the correct value, or do I have to establish a connection within my CheckData_Comany() method?
Your method SetConnection should be returning SqlConnection back like:
public SqlConnection SetConnection()
{
SqlConnection myConnection = new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
return myConnection;
}
and then you can have something like:
SqlConnection connection = set_conn.SetConnection();
and then pass it in SqlCommand constructor as parameter :
SqlCommand check_Company = new SqlCommand(query_string, connection);
Your complete method implementation would become :
public Boolean CheckData_Company(string[] items)
{
bool Exists = false;
Class_DB set_conn = new Class_DB();
SqlConnection connection = null;
try
{
connection = set_conn.SetConnection();
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
Exists = true;
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connection.Close();
}
return Exists;
}
and important thing to note is do not forget the close the connection finally by calling connection.Close(), otherwise it might cause eating up the resources that shouldn't happen when we are done with querying the database and we should release the resources occupied.

how can i solve the system.invalidcastexception

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlcon1 = new SqlConnection(#"Data Source=PRATHISTA;Initial Catalog=CRMT;Integrated Security=True");
sqlcon1.Open();
SqlCommand cmd1 = new SqlCommand("select * from Requirement", sqlcon1);
try
{
SqlDataReader sda1 = cmd1.ExecuteReader();
while (sda1.Read())
{
string sId = sda1.GetString("Requirement_Id");
// i get the error here;
}
sda1.Close();
sqlcon1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex);
}
}
As your id column isn't a string, the database doesn't return a string - you can only use the GetString method for string columns. You now have two options:
Using GetInt32
Directly getting the data from the reader
The first option is done like that:
var sId = sda1.GetInt32(index);
Remember however that the index here can't be of type string and must be an integer.
The second option is better (in my opinion) in that case:
var sId = (int)sda1["Requirement_Id"];
You can (of course) still use a string:
var sId = sda1["Requirement_Id"].ToString();

The ConnectionString property has not been initialized using c# asp.net

Hi i am getting the following error while trying to update my database using c# asp.net.
Error:
Server Error in '/' Application.
The ConnectionString property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
Source Error:
Line 33: catch (Exception e)
Line 34: {
Line 35: throw e;
Line 36: }
Line 37: }
I am explaining my code below.
index.aspx.cs:
protected void reject_Click(object sender, EventArgs e)
{
//LinkButton lbtn = (LinkButton)(sender);
//lbtn.BackColor = System.Drawing.Color.Red;
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
LinkButton lbtn = (LinkButton)grdrow.FindControl("accept");
LinkButton LRejectBtn = (LinkButton)grdrow.FindControl("reject");
// string status = grdrow.Cells[6].Text;
int healthId = int.Parse(lbtn.CommandArgument);
int result=0;
if (Convert.ToString(lbtn.BackColor) == "Color [Green]")
{
char updatedStatus = 'R';
result = objhealthCommentBL.updateStatusDetails(updatedStatus, healthId);
if (result == 1)
{
LRejectBtn.BackColor = System.Drawing.Color.Red;
lbtn.BackColor = System.Drawing.Color.WhiteSmoke;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status has updated successfully.')", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status couldnot updated')", true);
}
}
}
healthCommentBL.cs:
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
result = objhealthCommentDL.updateStatusDetails(updatedStatus, healthId);
return result;
}
catch (Exception e)
{
throw e;
}
}
healthCommentDL.cs:
namespace DataAccess
{
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getHealthCommentDetails()
{
try
{
con.Open();
DataSet ds = new DataSet();
string sql = "SELECT Health_Comment_ID,Health_ID,Health_Comment_Name,Health_comment_Email,Health_Comment_Message,Health_Comment_Website,Health_Comment_Status from T_Health_Comment";
sql += " order by Health_Comment_ID ASC ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
con.Close();
con.Dispose();
}
}
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
con.Open();
string query = "UPDATE T_Health_Comment SET Health_Comment_Status = #status WHERE Health_Comment_ID = #healthid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#healthid", healthId);
cmd.Parameters.AddWithValue("#status", updatedStatus);
result = cmd.ExecuteNonQuery();
con.Close();
return result;
}
catch (Exception e)
{
throw e;
}
}
}
}
I am getting the above error in healthCommentBL.cs file in catch statement.Here i can say that the commentstring is properly working in the getHealthCommentDetails method in healthCommentDL.cs file but at the same time it is not working for the 2nd method of this file.Please help me to resolve this error.
When you write your connection as;
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
It will be a field of healthCommentDL class, not a local variable. And it's properties (like ConnectionString) is not initialiazed. Instead of that, define your connections as a local variables in your methods. ADO.NET is pretty good at maintaining your connections as a local variables. Read: SQL Server Connection Pooling
public DataSet getHealthCommentDetails()
{
SqlConnection con = new SqlConnection(CmVar.convar);
and
public int updateStatusDetails(char updatedStatus, int healthId)
{
SqlConnection con = new SqlConnection(CmVar.convar);
A few things more;
You should always use parameterized sql. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.

Categories