When I try to run this, it gives me the following error message:
Conversion failed when converting the varchar value 'category_id' to data type int.
Here's my SQL and parameter code, I supposed it should work, but it doesn't.
mycmd.CommandText="SELECT * FROM categories WHERE #db_property = #property_id";
// This contains a string "category_id", which is correct.
mycmd.Parameters.Add("#db_property", SqlDbType.VarChar).Value=db_property_field;
// This contains an Int, referring to the category_id in database. As of now, this is 1
mycmd.Parameters.Add("#property_id", SqlDbType.Int).Value=property_id;
After I'm going through this code, I run it through a Reader, and that's where I get the error message above. Been asking teacher, and excellent students in my class, no one can find a clue on, where the problem is.
You shouldn't add field name as parameter. Try to change your script to include actual field id:
mycmd.CommandText = "SELECT * FROM categories WHERE category_id = #property_id";
mycmd.Parameters.Add("#property_id", SqlDbType.Int).Value = property_id;
I'm not sure about your structure, but try the following:
mycmd.CommandText = "SELECT * FROM categories WHERE Cast(#db_property as Int) = #property_id";
Your query is matching the two variables you are passing in so it will either return all the data or none of it! On top of that you are matching a char variable with an int. SQL will try to cast the char variable to an int.
#db_property = #property_id
should your query look like this?
SELECT * FROM categories WHERE db_property = #db_property AND property_id = #property_id
If you look at your statement you are comparing the two parameters. The WHERE clause is not on a table column ("categories") and the two parameters you are passing are different data types. VarChar and Int. When that command is executed the SQL engine is trying to compare two variables of different data types.
If you run the following SQL statements straight against SQL you will receive the same error.
DECLARE #Var1 VARCHAR(100)
DECLARE #Var2 INT
SELECT #Var1 = 'Test', #Var2 = 1
SELECT * FROM dbo.categories WHERE #Var1 = #Var2
You can get solution from the following address:
http://net-informations.com/csprj/data-providers/cs-procedure-parameter.htm
For your information I Just reshape the code and use it to my needs.
Code of Stored Procedure is as follow:
Create PROCEDURE [dbo].[PmSPValidate]
#a varchar(10)
AS
BEGIN
(SELECT AcctDsc,AcctAge
FROM dbo.tblCoa
WHERE AcctNo >= #a)
END
Code of C# :
private void btnThirdTrial_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlDataAdapter adapter;
SqlCommand command = new SqlCommand();
SqlParameter param;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=FIN03;Initial Catalog=CmsTest;Integrated Security=True";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.PmSPValidate";
param = new SqlParameter("#a",Account.Text.ToString ());
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(" Name " + ds.Tables[0].Rows[i][0].ToString() + " Age " + ds.Tables[0].Rows[i][1].ToString());
}
connection.Close();
}
Related
I declared already so why do I get an error?
conn.Open();
String strCount = "Select SUM(freight) AS TOTAL from Orders where EmployeeID = #employee AND Year(OrderDate)= #Oyear";
SqlCommand cmdCount = new SqlCommand(strCount, conn);
cmdSelect.Parameters.AddWithValue("#employee", DropDownList1.SelectedValue.ToString());
cmdSelect.Parameters.AddWithValue("#Oyear", RadioButtonList1.SelectedValue.ToString());
double intCount = (double)cmdCount.ExecuteScalar();
Label1.Text = intCount.ToString();
conn.Close();
You are adding the parameters to the wrong command.
Change the command name you add the parameters to, and it will work:
cmdCount.Parameters.AddWithValue("#employee", DropDownList1.SelectedValue.ToString());
cmdCount.Parameters.AddWithValue("#Oyear", RadioButtonList1.SelectedValue.ToString());
I want to reuse a parameterized query in a loop.
(This query is a simple example, I don't think I could make the loop inside sql and just return the needed rows)
Instead of
private String sql = "SELECT v FROM t WHERE VAL_1 = #param_1";
for (int n=1;n<10;n++)
{
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.AddWithValue("#param_1", n);
res = Convert.ToInt32(m.ExecuteScalar());
( ... )
}
I'd like to move the setup of the query outside the loop; something like
private String sql = "SELECT v FROM t WHERE VAL_1 = #param_1";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.Add("#param_1"); // does not exist
for (int n=1;n<10;n++)
{
m.Parameters.Set("#param_1", n); // does not exist
res = Convert.ToInt32(m.ExecuteScalar());
( ... )
}
So the server does not have to parse the same sql for each ilteration in loop.
Is that possible?
You can add a parameter with
m.Parameters.Add("#param_1", MySqlDbType.Int32);
and later in the loop assign a value with
m.Parameters["#param_1"].Value = n;
If you just need to run query for list of parms without do diffrent things on each result, You can create a string with a loop like that:
String where_str= VAL_1 = #param_1" OR VAL_1 = #param_2" OR VAL_1 = #param_3"...
String sql = "SELECT v FROM t WHERE " + where_str;
and then exec the query it will give the same result.
If you need to saparate results so you can make it with prepaerd statement. Also, I recommend you to read about stored procedure it may be the best soultion for you in some cases.
example for prepaerd statement: (more info in the link)
private static void SqlCommandPrepareEx(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(null, connection);
// Create and prepare an SQL statement.
command.CommandText =
"INSERT INTO Region (RegionID, RegionDescription) " +
"VALUES (#id, #desc)";
SqlParameter idParam = new SqlParameter("#id", SqlDbType.Int, 0);
SqlParameter descParam =
new SqlParameter("#desc", SqlDbType.Text, 100);
idParam.Value = 20;
descParam.Value = "First Region";
command.Parameters.Add(idParam);
command.Parameters.Add(descParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
command.ExecuteNonQuery();
// Change parameter values and call ExecuteNonQuery.
command.Parameters[0].Value = 21;
command.Parameters[1].Value = "Second Region";
command.ExecuteNonQuery();
}
}
Yes, this should be possible! Have a look for SQL Prepared Statements!
You can just use:
cmd = new MySqlCommand("SELECT * FROM yourTable WHERE condition=#val1", MySqlConn.conn);
In the loop add the parameters and prepare the command
cmd.Parameters.AddWithValue("#val1", value);
cmd.Prepare();
after the loop execute your query with
cmd.ExecuteNonQuery();
Yep, you can do all of those things but unless that's just an example you'd want to use IN with all the values or a join to a bulk loaded temp table if there are a large number of them. The reason is that each round trip to the DB has a significant overhead that you can reduce from n to 1 with either of those techniques.
I want to get the value to insert a table in C#,something like this:
begin
insert into bk_library(floor,section) values('foo2','bar')
returning id into :outid;
select *from bk_library where id=:outid;
end;
Unfortunately, I failed
error info: Kiss.Linq.Linq2Sql.Test.EntryPoint.TestInsertReturnId:
Oracle.DataAccess.Client.OracleException : ORA-06550: line 3, column
1: PLS-00428: an INTO clause is expected in this SELECT statement
[Test]
public void TestInsertReturnId()
{
int ret = 0;
string connstring = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=pdborcl)));User Id=system;Password=****;";
string sql = #"insert into bk_library(floor,section) values('foo','bar') returning id into :outid";
sql = getSqlString();
using (DbConnection conn = new OracleConnection(connstring))
{
conn.Open();
DbCommand command = conn.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
OracleParameter lastId = new OracleParameter(":outid", OracleDbType.Int32);
lastId.Direction = ParameterDirection.Output;
command.Parameters.Add(lastId);
ret = command.ExecuteNonQuery();
// this code work fine ,now I want to get the entire record
LogManager.GetLogger<EntryPoint>().Info("The new id ={0}", lastId.Value.ToString());
conn.Close();
}
Assert.AreNotEqual(ret, 0);
}
ParameterDirection should be ReturnValue
lastId.Direction = ParameterDirection.ReturnValue;
From < http://arjudba.blogspot.ch/2008/07/pls-00428-into-clause-is-expected-in.html?m=1>
You need to write SELECT * INTO some_variable FROM bk_library instead of SELECT * FROM bk_library because I assume you want to store the data retrieved somehow. Therefore you need to declare a new variable some_variable (I assume of type string) and modify your SELECT statement as above. The data from the statement will then be stored in your new variable.
Hope this helps
I am receiving the error, Must declare the scalar variable "#ID". Pointing at ExecuteScalar line. I looked on goggle and I think it has something to do with insert parameters for ID. Then again I read there could be a typo error. In my db I have declare column name as ID and Data Type as int, setting 'Is Identity' as Yes. As I am not going to insert ID column manually I think this is why I am having problem(s) and I don't know how to solve this problem.
What I am trying to do is insert username, login date and time. Update on the same column (same id column) when user logs out. Create a new column when user log in again and So on. I am using the similar code that I asked here and here when D Stanley helped me.
Thanks in advance if anyone can help me.
private int ID // forgot to add this.
{ get; set; }
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string value = cbRoles.Text;
switch (value)
{
case "Manager":
myCon.connectionString();
string dString = string.Empty;
SqlConnection thisConnection = myCon.dbCon;
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
using (var command = myCon.dbCon.CreateCommand())
{
command.CommandText = "SELECT * FROM tblPrivileges";
command.Parameters.AddWithValue("UserName", (txtUserName.Text));
command.Parameters.AddWithValue("Password", (txtPassword.Text));
thisConnection.Open();
var reader = command.ExecuteReader(); //strcomp
{
if (reader.HasRows)
{
while (reader.Read())
{
txtUserName.Text = reader["UserName"].ToString();
txtPassword.Text = reader["Password"].ToString();
MainWindow gobackB = new MainWindow();
gobackB.Show();
LoginSample goback = new LoginSample();
goback.Hide();
}
}
else MessageBox.Show("You have entered incorrect credentials. Please try again", "error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
myCon.dbCon.Close();
nonqueryCommand.CommandType = CommandType.Text;
nonqueryCommand.CommandText = "INSERT tblLoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime)";
//nonqueryCommand.Parameters.AddWithValue("#ID", SqlDbType.Int); this did not work
//nonqueryCommand.Parameters["#ID"].Value = this.ID; this did not work
nonqueryCommand.Parameters.AddWithValue("#UserName", txtUserName.Text);
nonqueryCommand.Parameters.AddWithValue("#LoggedInDate", DateTime.Now);
nonqueryCommand.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery(); // error pointing here
nonqueryCommand.CommandText = "SELECT #ID = SCOPE_IDENTITY()";
int id = (int)nonqueryCommand.ExecuteScalar();
// int id = Convert.ToInt32(nonqueryCommand.ExecuteScalar()); this line did not work
this.ID = id;
myCon.dbCon.Close();
break;
The problem is still that you're trying to use the same "scope" with two different SQL commands. Even thought they are the same "variable" in C# in SQL they have different scope.
You'll need to execute both statements in one command and add the #ID parameter as an Output parameter in order to insert and get the identity out:
nonqueryCommand.CommandType = CommandType.Text;
nonqueryCommand.CommandText = "INSERT tblLoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime); " +
"SELECT #ID = SCOPE_IDENTITY()";
nonqueryCommand.Parameters.AddWithValue("#UserName", txtUserName.Text);
nonqueryCommand.Parameters.AddWithValue("#LoggedInDate", DateTime.Now);
nonqueryCommand.Parameters.AddWithValue("#LoggedInTime", DateTime.Now);
nonqueryCommand.Parameters.Add("#ID",SqlDbType.Int).Direction = ParameterDirection.Output;
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery();
int id = (int)nonqueryCommand.Parameters["#ID"];
Here:
nonqueryCommand.CommandText = "SELECT #ID = SCOPE_IDENTITY()";
your SQL assigns a value to a variable that is not declared. Since you are using ExecuteScalar, you probably just mean:
nonqueryCommand.CommandText = "SELECT SCOPE_IDENTITY()";
Note that you might need to cast it - it may come back as decimal.
I have searched and tried different things for the past week or so and my problem is possibly to specific to find an answer through google.
If I execute this query in SQL Server Management Studio and replace the parameter #zoekterm with '%something%', it works fine and returns the result that I want. But when I call the same procedure from C# it returns nothing.
Is this a bug or am I just that stupid?
Here's code of stored procedure and function in C#, (I know I should have used switch case...)
Stored procedure:
-- =============================================
-- Author: Daan
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[quick_bedrijf]
-- Add the parameters for the stored procedure here
#zoekterm varchar(100) = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT bedrijf.bedrijf_nr, bedrijf.zoeknaam, bedrijf.plaats
FROM bedrijf
WHERE zoeknaam LIKE #zoekterm AND NIETactief = 0
ORDER BY bedrijf.zoeknaam, bedrijf.plaats
END
C#:
private void snel_zoek2()
{
listView1.Items.Clear();
con.Open();
if (type == 1)
{
command1 = new SqlCommand("quick_project", con);
colnum = 5;
}
else if (type == 2)
{
command1 = new SqlCommand("quick_bedrijf", con);
colnum = 3;
}
else if (type == 3)
{
command1 = new SqlCommand("quick_persoon", con);
colnum = 4;
}
command1.CommandType = CommandType.StoredProcedure;
SqlParameter zoekterm = command1.Parameters.Add("#zoekterm", SqlDbType.VarChar, 100);
zoekterm.Direction = ParameterDirection.Input;
//command1.Parameters.Add(new SqlParameter("#zoekterm", SqlDbType.VarChar)).Value = " '%zee%'";// + textBox2.Text.ToString()+
zoekterm.Value = "'%"+textBox2.Text.ToString()+"%'";
// MessageBox.Show(zoekterm.Value.ToString());
SqlDataAdapter adapt = new SqlDataAdapter();
DataTable dt = new DataTable();
adapt.SelectCommand = command1;
adapt.Fill(dt);
dataGridView1.BindingContext = new BindingContext();
dataGridView1.DataSource = dt;
con.Close();
}
You don't put the quotes into the parameter (those are to signify a literal); it should be:
zoekterm.Value = "%"+textBox2.Text+"%";
It is failing currently because if the text is "abc", it is looking for a string that starts and ends with a single quote and includes "abc". In SQL terms, you were asking it for:
LIKE '''%abc%'''