Reputation: 85
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;
Upvotes: 1
Views: 134
Reputation: 10612
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();
Upvotes: 1
Reputation: 14024
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();
}
Upvotes: 1
Reputation:
change
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = prime";
to
cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = 'prime'";
Upvotes: 1