Search and display certain table element - c#

I'm trying to search my local database table and simply display all it's columns.
I start my sending in
SearchID("1234");
My code so far:
private static void SearchID(string CostumerID)
{
string conStr = #"Data Source = C:\Users\secwp_000\documents\visual studio 2012\Projects\Module5\Module5\Orderdatabase.sdf";
DataSet ds = new DataSet();
SqlCeConnection con = new SqlCeConnection(conStr);
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con);
SqlCeDataReader dr = cmd.ExecuteReader();
SqlCeDataAdapter adapt = new SqlCeDataAdapter(cmd);
adapt.Fill(ds, "Order");
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
}
Where am I thinking wrong?
It stops on
SqlCeDataReader dr = cmd.ExecuteReader();
saying i don't have a connection. But just sounds wierd, because I've just had connection..

You have to open connection using
If(con.state.toString()=="closed")
con.open();
I observe a fault in your query why are you compare your result after fetch from database.you can directly filter in SQL query
Select * from order where table.customer_Id = customerId

You have a connection but you haven't opened it yet:
con.Open();
adapt.Fill(ds, "Order");
con.Close();
In addition you should use using statements for disposable objects like SqlConnection and SqlCommand to make sure they will be disposed properly:
using(SqlCeConnection con = new SqlCeConnection(conStr))
using(SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con))
{
}

I feel so stupid for not seeing this, haha. And it worked! But it wont display anything from the table,
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
Following instructions given to me, there is nothing wrong with this code, and it could display Order with costumerID 1234.

Related

WPF C# Getting error when moving back and forth b/w Two Combo boxes items selection

I have 02 combo box as shown [Combo Boxes]
When i move back and forth for selection of items b/w Combo Boxes(Category and Model No.) i get the following error
enter image description here
My C# sharp code is given below
try
{
con.Open();
string CmdString = "select ProductID from Product where ModelNo='" + comboModel.SelectedItem.ToString() + "'";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable("Product");
sda.Fill(dt1);
foreach (DataRow dr in dt1.Rows)
{
txtProductID.Text = dr["ProductID"].ToString();
}
con.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
con.Close();
}
Get rid of con.Open();. Obviously the connection was already open from an earlier operation somewhere else or a prior run of this code.
That being said, you should probably not be keeping connections open unless you need them, because you run the risk that they aren't ever closed properly. You should use the disposable pattern, like this:
using (var con = new SqlConnection(myConnStr))
{
// do your query, etc.
}
This will automatically close the connection and dispose of the resources.
Your connection is opened somewhere else. Try putting it into using block, this way it will be disposed of automatically and is best practice for connections:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string CmdString = "select ProductID from Product where ModelNo='" +
comboModel.SelectedItem.ToString() + "'";
SqlCommand cmd = new SqlCommand(CmdString, connection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable("Product");
sda.Fill(dt1);
foreach (DataRow dr in dt1.Rows)
{
txtProductID.Text = dr["ProductID"].ToString();
}
}

Retrieving value from sql ExecuteScalar()

I have the following:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
Program.defaultCollection = (String)cmd.ExecuteScalar();
And I want to get the second column after executing the statement. I know it will return only one row with two columns
I have read online that I will have to read each row of the result, is there any other way?
ExecuteScalar gets the first column from the first row of the result set. If you need access to more than that you'll need to take a different approach. Like this:
DataTable dt = new DataTable();
SqlDataAdapater sda = new SqlDataAdapter(sql, conn);
sda.Fill(dt);
Program.defaultCollection = dt.Rows[0]["defaultCollection"];
Now, I realize that the field name may not be defaultCollection, but you can fill that in.
From the MSDN documentation for ExecuteScalar:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Now, as a final bit of advice, please wrap all ADO.NET objects in a using statement. Like this:
using (SqlConnection conn = new SqlConnection(connString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
// do something with `dt`
}
this will ensure they are properly disposed.
And I want to get the second column after executing the statement
It is not possible with execute scalar.
is there any other way
You have 2 options here either to use SqlDataAdapter or SqlDataReader.
For you using DataReader is a recommended approach as you don't need offline data or do other worh
by using SqlDataAdapter
using (SqlConnection c = new SqlConnection(
youconnectionstring))
{
c.Open();
/
using (SqlDataAdapter a = new SqlDataAdapter(sql, c))
{
DataTable t = new DataTable();
a.Fill(t);
if(t.Rows.Count > 0)
{
string text = t.Rows[0]["yourColumn"].ToString();
}
}
}
by using DataREader
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//read data here
string text = reader.GetString(1)
}
reader.Close();
}
SqlCommand.ExecuteScalar() can be used only when the result have just one row and one column.
If you need more than one column to be returned, you should use something like this:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.Read())
{
Program.defaultCollection = (String)rdr["Column1"];
Program.someOtherVar = (String)rdr["Column2"];
}
}
rdr.Close();
}
That will be the fastest way.
You can use a DataReader and read only the first column like:
IDataReader cReader = cmd.ExecuteReader();
if(cReader.Read())
{
string cText = cReader.GetString(1); // Second Column
}
ExecuteScalar only returns one value. You have to make sure your query only returns that value.
String sql = "SELECT temp.defaultCollection FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
On a side note, read on SqlParameter. You don't want to concatenate values like that, you'll have a problem when the collection property contains a quote.

How to populate data from SQL Server database columns to textboxes

I want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..

OutOfMemoryException in my application, I tried to use using and dispose()!

I've just read all the answers about the same problem but they have not helped.
This is a part of my c# code that is too long. It has a lot of SQLConnections and 2 timers.
Indirizzo nuovoInd = new Indirizzo();
SqlConnection cn = new SqlConnection(nuovoInd.OttieniIP());
string strSql = "INSERT INTO Pietanze(nome,prezzo,ingredienti,cod_cat) VALUES ('"+nome+"','"+prezzo+"','"+ingredienti+"','"+contCat+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
or
public static float GetCoperti(int codOrdine)
{
float copertiTot = 0;
List<Ordine> ordini = new List<Ordine>();
VisualizzaOrdini.Form1.Indirizzo nuovoInd = new VisualizzaOrdini.Form1.Indirizzo();
SqlConnection cn = new SqlConnection(nuovoInd.OttieniIP());
string strSql = "SELECT codo,tavolo,InsertDate,nCoperti,costoCoperti FROM Ordini, Riga_Ordine, Coperti where codo=cod_or and cod_or = '"+ codOrdine + "' ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(strSql, cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Ordine currO = new Ordine();
currO.Data = Convert.ToDateTime(dr["InsertDate"]);
currO.Coperti = (int)dr["nCoperti"];
currO.PrezzoCoperto = Convert.ToSingle(dr["costoCoperti"]);
currO.Tavolo = dr["tavolo"].ToString();
currO.Codice = (int)dr["codo"];
copertiTot = (currO.PrezzoCoperto * Convert.ToSingle(currO.Coperti));
ordini.Add(currO);
}
return copertiTot;
}
I'm struggling with the fact that the code is throwing an OutOfMemoryException. What might be causing this? How do I resolve it?
It may be the problem that you are not Closing your SqlDataReader object after fetching records, You have to close it explicitly.
dr.Close();
And also, Close your connection after closing reader, or use using block as suggested by Habib.
cn.Close();
First, having your database connection open for the full execution of code is bad practice. Assign the execute statement to some DataTable. It will provide you the local copy of the database. It's also more convenient to process and you surely don't get out of memory exceptions.
Datatable DTab = cmdexecuteReader();
DataSet DSet = cmdexecuteReader();
Both Will give you expectedd results always.

asp.net print the results of a sql command

I have the following sql command:
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
How can i output the results of the following command in C# to my webpage?
If you are looking for the introductory: "How to get data on a web page?" answer, then maybe this is a little more helpful:
Add a new page MyPage.aspx to your
web application
Add a GridView to that page
On Page_Load do the code
below
{
string strSQLconnection =
"Data Source=dbServer;Initial Catalog=yourDatabase;Integrated Security=True";
SqlConnection con = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
con.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
You will need to execute the SQL command, then iterate through the data. Assuming this query returns one row, your code might look like:
using (var reader = cmd.ExecuteReader()) {
if (!reader.HasRows) {
// User not found
}
else {
reader.Read(); // Advance to first row
// Sample data access
var name = reader["name"];
var otherColumnValue = reader["otherColumnName"];
}
}

Categories