must declare variable scalar - sql

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

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);
}

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

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.

how to insert row in SQL database in ADO.Net Connection oriented mode

I have a database in which a table has name Registration which is used to register the user.
It has only two column one is Username and one is password.
A page named Register.aspx is used for registering the member which have two textbox one is for taking Username(textbox1) and one is for taking password(textbox2) and one button for insert these value in database.
The Main problem is that we cannot write statement like this :
Insert into Registration (Username, password)
values ('TextBox1.text','TextBox2.text')
I am using ADO.net Connection oriented mode, I googled but I didn't find any way to insert row in SQL database in connected mode. Please provide me a idea for inserting this row?
ADO.NET has DataReader which supports Connected mode. All else are disconnected.
DataReader is connected architecture since it keeps conneection open untill all records are fetched
If you want to insert in ADO.NET then you should perform the following steps:
private void btnadd_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
Execute command by calling following method................
1.ExecuteNonQuery()
This is used for insert,delete,update command...........
2.ExecuteScalar()
This returns a single value .........(used only for select command)
3.ExecuteReader()
Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
try
{
using (var connection = new SqlConnection(yourConnectionString))
{
string queryString = "Select id, name, age from Table where name = #name";
using (var command = new SqlCommand(queryString, Connection))
{
command.Parameters.AddWithValue("#name", name);
Connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
item = new Item(long.Parse(dataReader[0].ToString()),
dataReader[1].ToString(),
int.Parse(dataReader[2].ToString()));
}
dataReader.Close();
}
}
}
catch (Exception ex)
{
// if exception will happen in constructor of SqlConnection or Command, the // resource can leak but Dispose method will never be called, couse the object was not created yet.
// Trace and handle here
throw;
}
finally
{
}
But ADO.net is useless for enterprice development. You have to have and abstraction from Data Acess Layer and go to entities, not table records
Use the ORM, Luke!
using System.Data.SqlClient;
string cnstr = "server=.;database=dbname;user=username;password=password;";
SqlConnection con = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand { Connection = con };
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
//something;
}
finally
{
if (con != null)
con.Close();
}

sqlcommand for updation

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.