using(OleDbDataAdapter adapter = new OleDbDataAdapter("select * from xxx where id=@id","your conn str"))
{
DataTable dt = new DataTable();
adapter.SelectCommand.Parameters.AddWithValue("@id",your real value here);
adapter.Fill(dt);
//Do what you want to dt……
}
R0ck0n
0 Points
2 Posts
Need a simple example retrieving data record from database with a query
Jun 15, 2012 07:41 AM|LINK
Hi,
I would like to show data into several textfields using the following query
"select *from Main where ID= "+ txtMainIndex + "";
I have tried but have difficulties showing in the textfields, no errors but no data in the textfields as well.
What is the best and efficient way to do it? please someone help
public partial class Main : System.Web.UI.Page
{
SqlConnection con;
//ConnectionString variable
protected void Page_Load(object sender, EventArgse)
{
con =new SqlConnection(ConfigurationManager.ConnectionStrings["BCBCPConnectionString"].ConnectionString);
}
protected void btnSearch_Click(object sender, EventArgs
e)
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand
();
cmd.CommandText = "select *from Main where ID= " + txtMainIndex + "";
cmd.Connection = con;
//cmd.Parameters.Add(new SqlParameter(" txtMainIndex" , System.Data.SqlDbType.Int, 5, "ID"));
//cmd.Parameters["ID"].Value = txtMainIndex.Text;
SqlDataReader rdr = null
;
rdr = cmd.ExecuteReader();
while
(rdr.Read())
{
txtXMLData.Text = rdr["Material"].ToString();
txtWeight.Text = rdr["Weight"].ToString();
}
}
catch (Exceptionex)
{
Console.WriteLine("An error occurred: '{0}'", ex);
}
finally
{
if (con.State == ConnectionState
.Open)
con.Close();
}
}
}
hans_v
All-Star
35986 Points
6550 Posts
Re: Need a simple example retrieving data record from database with a query
Jun 15, 2012 07:50 AM|LINK
The best (and more important, most secure) way is to use parameters
http://www.mikesdotnetting.com/Article/113/Preventing-SQL-Injection-in-ASP.NET
Decker Dong ...
All-Star
118619 Points
18779 Posts
Re: Need a simple example retrieving data record from database with a query
Jun 16, 2012 01:09 AM|LINK
My addition to hans_v:)
【Sample codes】
using(OleDbDataAdapter adapter = new OleDbDataAdapter("select * from xxx where id=@id","your conn str")) { DataTable dt = new DataTable(); adapter.SelectCommand.Parameters.AddWithValue("@id",your real value here); adapter.Fill(dt); //Do what you want to dt…… }