I have to fetch data from database and enter into textbox in my form.My Form has textboxes and gridview(for some textboxes alone).I have to fetch data from database based on selected grid view cell=PROJECTNAME and enter into other textboxes matching that criteria.
I have done my coding part for single textbox and its showing "{"ORA-00904: \"PRIME\": invalid identifier"}"
Kindly help me with the following
OracleConnection con = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TEST"].ToString());
con.Open();
OracleCommand cmd = con.CreateCommand();
string prime = gdDisplay.SelectedRow.Cells[1].Text;
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = prime";
string str= cmd.ExecuteScalar().ToString();
txtDescription.Text = str;
You can do something like this
There is no need to keep calling .ToString() as getValue is already a string. and also need to take care that the string values has to be quoted in the '' single quotes.
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = 'prime'";
var str= cmd.ExecuteScalar();
We can just put a check to see if the value is null
if (str!= null) {
txtDescription.Text = str.ToString();
}
and apart from that you could use this as well
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = 'prime'";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
txtDescription.Text = reader["DESCRIPTION"].ToString().Trim();
}
change
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = prime";
to
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = 'prime'";
You may get result by changing the query to
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = 'prime'";
i.e by adding quotes to the passing identifier. But it is not safe to do so and might expose to sql injection problems. For example if someone tries to search with a keyword like --> Where ProjectName = 'Anil's Project', note there comes three quotes causing confusion to the query
A safe way and a good practice from the beginning itself is using parameters. Its simple. Do like
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = #ProjectName";
cmd.Parameters.AddWithValue("#ProjectName", "prime"); // don't use additional quotes inside like "'prime'"
string str= cmd.ExecuteScalar().ToString();
Related
Error:
Conversion failed when converting the nvarchar value 'select TopicID from Topic where TopicName='Data Structure'' to data type int
Code:
public void BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();
string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";
string strquery3 = "select i.name ,i.score from info as i,Topic as t where i.topic_id=#topicid";
SqlCommand cmd = new SqlCommand(strquery3,sqlcon);
cmd.Parameters.AddWithValue("#topicid",strquery2);
cmd.Connection = sqlcon;
SqlDataReader dr;;
this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();
sqlcon.Close();
}
}
Could anyone tell me where I am going wrong? Any help would be appreciated.. Please reply as soon as possible.. Thanks in advance..
You are passing the in the entire query not the topic id in this line here
cmd.Parameters.AddWithValue("#topicid",strquery2);
It is then taking that as a parameter and adding it to the following query. If this is a subquery, you can always execute it first and then use the result in the paramter.
But the reason that it is failing is because you are essentially trying to compare a String to an int by passing in the query string like that.
I think what you want in cmd.Parameters.AddWithValue("#topicid",strquery2); is the value returned by strquery2???? , the topic id will get generated if you execute this query first and the result of this will be used instead of query itself
Is that what you want ??
can you tried with below code, I have not tested but its should work for you
public void BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();
//Equal is not working when subquery return more records
string strquery2 = "select i.name ,i.score from info as i,Topic as t where i.topic_id in (select TopicID from Topic where TopicName=#TopicName)";
SqlCommand cmd = new SqlCommand(strquery2, sqlcon);
cmd.Parameters.AddWithValue("#TopicName", ddltopic.SelectedItem.Text);
cmd.Connection = sqlcon;
SqlDataReader dr; ;
this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();
sqlcon.Close();
}
Not an actual answer, but comments are too short for this.
This code is vulnerable to SQL injection:
string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";
Imagine that at some point in the future someone (you or someone else who is modifying your code) decides to replace the drop-down list with a combo box? Now imagine someone enters this text into the combo box:
'; TRUNCATE TABLE Topic; --'
Now your SQL server is going to do this:
select TopicID from Topic where TopicName = '';
TRUNCATE TABLE Topic; --'
Learn to use parameters.
I need to bind parameters on ODBC query from C#. This is the sample code, but VS tells me that there's one parameter missing.
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM user WHERE id = #id";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
What is the syntax for binding values on ODBC?
Odbc cannot use named parameters. This means that the command string uses placeholders for every parameter and this placeholder is a single question mark, not the parameter name.
OdbcCommand.Parameters
Then you need to add the parameters in the collection in the same order in which they appear in the command string
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE id = ?";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
You have also another problem, the USER word is a reserved keyword per MS Access Database and if you want to use that as field name or table name then it is required to enclose every reference with square brackets. I strongly suggest, if it is possible, to change that table name because you will be hit by this problem very often.
use "?" in place of # if you are using ODBC.
Try to do as follows:
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM user WHERE id = ?";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
To use ODBC parameterized LIKE carry out as follows, i.e. you do not use the typical single quotes or even put the % in the CommandText (Furthermore I think perhaps the %? has a special meaning for Oracle? :
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE name LIKE ?";
cmd.Parameters.AddWithValue("#fieldName", OdbcType.NVarChar).Value = "%" + nameFilter + "%";
I have 2 radio buttons in a panel and I save their value as numeric (0 and 1) here is the code for insert into SQL:
String typdop="1";
if(rb_a.Checked)typdop="0";
("INSERT INTO zajezd(typdop)values(#typdop")
prikaz.Parameters.AddWithValue("typdop", typdop);
and for reading I use this:
SqlCommand novyprikaz = new SqlCommand("SELECT * FROM zajezd WHERE akce="+nc_zajezd_vyber, spojeni);
con.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();
if (precti.Read())
{
try
{ rb_a.Checked = precti(32);}
the visual studio gives me an error, because I don't know how to change Checked value of rb_a, I would like to read it like this:
If in database is saved 0 - Check rb_a
If 1 I would like to check rb_b
May someone help solve this out?
Thanks
Too many details are missing, but you could try this code.
string cmdText = "SELECT * FROM zajezd WHERE akce=#p1";
SqlCommand novyprikaz = new SqlCommand(cmdText, spojeni);
novyprikaz.Parameters.AddWithValue("#p1", nc_zajezd_vyber);
spojeni.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();
if (precti.Read())
{
try
{
bool check = Convert.ToBoolean(precti(32));
if(check)
rb_b.Checked = true;
else
rb_a.Checked = true;
}
}
Please take note; if your nc_zajezd_vyber is not of the correct datatype required by the database field, your query could fail to retrieve anything. AddWithValue assumes the datatype of the parameter from the value passed. If this is not correct....
For the same reasong (AddWithValue wants the exact datatype expected by the database field, then your insert code should be something like this:
int typdop=1;
if(rb_a.Checked) typdop=0;
string cmdText = "INSERT INTO zajezd(typdop)values(#typdop)";
SqlCommand prikaz = new SqlCommand(cmdText,spojeni);
prikaz.Parameters.AddWithValue("typdop", typdop);
spojeni.Open();
prikaz.ExecuteNonQuery();
....
I need to retrieve a value from a field in database. I have the used following code. but the value checkOrderId (which I need) shows the SQL string instead of the value from database. I don't know why it is doing so. Could somebody help me please?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
I am new and dont have reputation to answer my question immediately. With everybody's help, i got this one solved...Great help, thanx everybody...following is my code.
string connectionString = "Data Source = EAEDEV;Initial Catalog = GIS; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
You need to execute the query and check the results, here you are just comparing a string with the query SQL.
Please see here
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03
for a tutorial.
Your expectation of the result being set into checkOrderId is incorrect. In this instance checkOrderId is just the query to execute and not the actual result.
You need to read the value back from executing the command:
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand("Select TOP 1 OrderID From [GIS].[SecondaryTraffic].[PotentialBackHauls] ORDER BY InsertDate DESC", connection))
{
connection.Open();
object result = comm.ExecuteScalar(); // This is the key bit you were missing.
if (result != null)
{
// You can cast result to something useful
int orderId = (int)result;
}
} // Both comm and connection will have Dispose called on them here, no need to Close manually.
ExecuteScalar returns the value in the first cell (ie, column 1 row 1) as an object that you can cast to a better type (depending on what type it was in the result-set schema).
If you need to read multiple values, you need to look at ExecuteReader.
There are also other ways of doing this using output parameters, but that would pollute the point of the answer.
You can add space to your query
"Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
Nota : I suggest you to use AddWithValue method with your parameter
string checkOrderId = "Select TOP 1 OrderID From #tableName ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
cmd.Parameters.AddWithValue("#tableName", tableName );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
You don't actually run your command anywhere. Instead of the commented-out cmd.ExecuteNonQuery, you should look into the ExecuteScalar method, which allows you to read back a single result value from a query - which is what your query returns.
Add
int i = (Int32) cmd.ExecuteScalar();
right after
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
then the variable i will contain the order id
No, this is not correct. You are comparing the variable orderId to your query string. I doubt that's what you want to do. I imagine you'd be better off calling cmd.ExecuteScalar() to retrieve the actual OrderID value. As noted by other answers, your query string is missing a space. But most importantly, it is bad practice to construct SQL queries in code. Although I can't see a security issue with this code, if you continue to use this method you will probably write code that is vulnerable to SQL injection. I recommend you learn to either use parameters or LINQ to build your queries.
i am trying to retrieve latest data from my database table.
i am using max(columnName) but not having result to my liking.
i keep getting column name instead of any value
please help me out in this...
the code for retrieving max value is like this
dbConnection dbCon = new dbConnection();
con = dbCon.doConnection();
SqlCommand cmd = new SqlCommand();
String query = "select max(studentNo) from studentInfo;";
cmd.Connection = con;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
String x=reader["studentNo"].ToString();
}
here the studentNo is the column name whose value i need to extract and it is of int type
while printing the string x on my application i get studentNo instead of the value.
now i am short of clue to solve the prob because i can't find anything wrong with the code.
do help me in this one
The problem is in the way you are accessing the value, you can change two things here. Either access the reader by index or name the column appropriately in the query.
select max(studentNo) as StudentNo from studentInfo;
Your query outputs one row and one column of data, so you might consider using ExecuteScalar() instead of ExecuteReader():
dbConnection dbCon = new dbConnection();
con = dbCon.doConnection();
SqlCommand cmd = new SqlCommand();
String query = "select max(studentNo) from studentInfo;";
cmd.Connection = con;
cmd.CommandText = query;
String x = cmd.ExecuteScalar().ToString();
You need to give alias to your select after applying aggregate function
i.e. select max(studentNo) as NO from studentInfo
and while reading it
String x=reader["NO"].ToString();
First you need to set the correct alias do the column:
select max(studentNo) as 'studentNo' from studentInfo;
And second, you may want to assign a database to the table:
select max(studentNo) as studentNo from databaseName..studentInfo;