简体   繁体   中英

Have to fetch data from database and enter into textbox

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;

change

cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = prime";

to

cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = 'prime'";

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

You may get result by changing the query to

cmd.CommandText = "Select DESCRIPTION FROM CMPPOJECT WHERE PROJECTNAME = 'prime'";

ie 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM