hi guyz in this method i m just adding the values to the db.
temp is a object.
the field value and variables in the object re havin the same name..
dono y this error s comin
plz
help me out...
public virtual void Save_input_parameter_details(Test_Unit_BLL temp )
{
SqlConnection con;
con = new SqlConnection("Data Source=VV;Initial Catalog=testingtool;User ID=sa;Password=sa;");
con.Open();
SqlCommand cmd, cmd2, cmd3;
//try
//{
for (int i = 0; i < temp.No_Input_parameters; i++)
{
cmd2 = new SqlCommand("insert into Input_parameter_details values(#Input_Parameter_name,#Input_Parameter_datatype,#noparams,#class_code", con);
cmd2.Parameters.AddWithValue("#Input_Parameter_datatype", temp.Input_Parameter_datatype[i]);
cmd2.Parameters.AddWithValue("#Input_Parameter_name", temp.Input_Parameter_name[i]);
cmd2.Parameters.AddWithValue("#noparams", temp.No_Input_parameters);
cmd2.Parameters.AddWithValue("#class_code",temp.class_code);
cmd2.ExecuteNonQuery();
}
//}
//catch (Exception ex)
// {
// MessageBox.Show("error"+ex);
// }
}
It may be failing based on the unknown actual sequence of columns its trying to push the data into. You are implying the first X number of columns. You may need to be explicit in your SQL such as :
insert into YourTable ( Fld1, Fld2, Fld3 ) values (#ParmVal1, #ParmVal2, #ParmVal3 );
Then do your parameters.add with values... Additionally, you MAY want to make sure your added parameters are in the same sequence as your SQL statement lists them too.
Do the columns in the table line up with the parameters as you have them listed (1st = input_parameter_name, 2nd = input_parameter_datatype, etc.)?
Related
I am writing a program to maintain an inventory of medicine in our store.
I have a Add to cart list, which opens up the SQL connection and delete 1 quantity from the entire stock where the parameter is #medicine
My addToCart listBox's code looks like this
using (SqlConnection conn = new SqlConnection(cstring))
{
using(SqlCommand cmd = new SqlCommand("Update Medicine set Quantity = Quantity - 1 where Name = #medicine", conn))
{
conn.Open();
foreach(string item in cartMedicine)
{
cmd.Parameters.AddWithValue("#medicine", item);
cmd.ExecuteNonQuery();
}
conn.Close();
listMedicine.Items.Clear();
}
}
Now I want to loop my cartMedicine list to get all the names stored in the listbox one by one. But I am getting the error message that,
The variable name '#medicine' has already been declared. Variable names
must be unique within a query batch or stored procedure.'
How can I use the same logic of giving an Adhoc statement each time for each inventory in my Item's list?
Don't add the parameter over and over again but add it once and then just set its value. "AddWithValue is Evil" anyway.
...
SqlParameter sqlParameter = cmd.Parameters.Add("#medicine", SqlDbType.<data type>, <length>)
foreach (string item in cartMedicine)
{
sqlParameter.Value = item;
cmd.ExecuteNonQuery();
}
...
Replace <data type> and <length> with the proper values for the data type of medicine.quantity in the database.
I am trying to add the values of a column of a table. My table looks like this:
enter image description here
I want to add the values of months column for a specific id. My code looks like this:
public int MonthSum(int id)
{
SqlConnection connection = new SqlConnection(connectionString);
string query = "select sum(months) from PayTable where ID=#ID group by ID";
SqlCommand command = new SqlCommand(query,connection);
command.Parameters.Clear();
command.Parameters.Add("ID", SqlDbType.Int);
command.Parameters["ID"].Value = id;
connection.Open();
int total = (int)command.ExecuteScalar();
connection.Close();
return total;
}
Why I am getting exception here??
Since you don't provide more information about the exception, it's only guessing, but you may have a problem adding the parameter as "ID" instead of "#ID". I think that SqlCommand expects the name with the #.
Here some Microsoft documentation with an example very similar to what you are doing.
When querying an Access 2000 database, using:
schemaTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Indexes, New Object() {Nothing, Nothing, tableName})
Where cn is a valid and open connection, schemaTable always contains zero rows, despite the tableName specified having many indexes.
This documentation, here http://msdn.microsoft.com/en-us/library/cc668764.aspx suggests that MS Access provides this information.
What gives?
It appears that when retrieving .Indexes the third member of the restrictions array corresponds to the Index name, not the Table name. So to retrieve the indexes for a given table it looks like we need to retrieve all of the indexes (no restrictions) and then filter out the ones we don't want.
The following C# code works for me:
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = myConnectionString;
con.Open();
object[] restrictions = new object[3];
System.Data.DataTable table = con.GetOleDbSchemaTable(OleDbSchemaGuid.Indexes, restrictions);
// Display the contents of the table.
foreach (System.Data.DataRow row in table.Rows)
{
string tableName = row[2].ToString();
if (tableName == "Clients")
{
foreach (System.Data.DataColumn col in table.Columns)
{
Console.WriteLine("{0} = {1}",
col.ColumnName, row[col]);
}
Console.WriteLine("============================");
}
}
con.Close();
}
Below is the code for my Select * Function - It WORKS well and does everything great until i change the SQL string from Select * From Company to
query = "Select * From #1";
and then do the following
query = "Select * From #1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("#1", SQLTables.Company);
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
The DBMS keeps sending back "Query incomplete" - I assume The Command variable is sending the string query through without changing the Parameter from #1 to Company
Here is a piece of code (mine) where this does work. This is an insert statement rather that a select - Correct me if i am wrong but should it not also work with the SELECT aswell
private void MainActionsInsert(string Action, bool Checked)
{
OleDbCommand Command = new OleDbCommand("INSERT INTO MainActions Values (ID, Action, BoolValue)", DataBaseConnection);
//Add Parameters
Command.Parameters.AddWithValue("ID", GenerateID());
Command.Parameters.AddWithValue("Action", Action);
Command.Parameters.AddWithValue("BoolValue",Checked);
//Add Command
MainActionsAdapter.InsertCommand = Command;
//Execute Agains DataBase
Command.ExecuteNonQuery();
//Accept Changes
}
`
OLEdb doesn't recognize named parameters. You must use ? in the query text.
However, you also can't use dynamic table names with parameterized queries, so even using a ? will not help.
You need to use full dynamic SQL, though that can open you up to SQL Injection. Make sure you read the full article I linked.
OleDbCommand Does accept Parameterized SQL just not in the From Clause - It Has to be either in a WHERE clause or something like that. Like you said it Worked with the insert function because it expects "parameters" there. For example this will work
query = "Select * From Company Where #param = 1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("param", "ID");
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
Funny though that it doesn't work for the Select part though
I am trying to write three variables into a database table. The code I have is:
sqlCmd.CommandText = "INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(StudentNumber.ToString() , Time.ToString() , Total.ToString())" + dbConnection;
sqlCmd.ExecuteNonQuery();
sqlTran.Commit();
dbconnection is the name of the connection. It does not do anything. It is in a try-catch but goes straight to catch.
Thanks in advance.
You should
avoid concatenating together your SQL statement - avoid SQL injection attacks! Use parametrized queries instead!
use using blocks for your SqlConnection and SqlCommand objects
Try something like this:
string _connString = "........";
string queryStmt =
"INSERT INTO dbo.PortfolioValues(StudentNumber, TimeStamp, PortfolioValue) " +
"VALUES(#StudentNumber, #TimeStamp, #TotalValue)";
using(SqlConnection _con = new SqlConnection(_connString))
using(SqlCommad _cmd = new SQlCommand(queryStmt, _con))
{
// create paramters and set values
_cmd.Parameters.Add("#StudentNumber", SqlDbType.Int).Value = StudentNumber;
// do the same for the other two parameters
try
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
catch(Exception exc)
{
// handle exception
}
}
StudentNumber.ToString() cannot be contained in a query! It's java code not sql...
//Am asuming you are using C# and the System.Data.SqlClient
//here is how you might do what you want
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
//so that you use it this way:
String query = String.Formart("INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(\"{0}\",\"{1}\",\"{2}\")",StudentNumber.ToString() , Time.ToString() , Total.ToString());
String connectionString = "your connection string";
CreateCommand(query,connectionString);