string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr = "select * from quant_level1";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
DataSet data = new DataSet();
int i = data.Tables["quant_level1"].Rows.Count;
Label2.Text = i.ToString();
use
string cmdstr = "SELECT COUNT(*) FROM quant_level1";
With com.ExecuteScalar()
using(OleDbConnection conn = new OleDbConnection(constr))
using(OleDbCommand command = new OleDbCommand(cmdstr, conn))
{
conn.Open();
int count = (int)command.ExecuteScalar();
}
ExecuteScalar returns the first column of the first row in the result set returned by the query, here it give you row count.
you can use OleDbDataReader as you try in your code sample. but need to change the logic bit.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("select * from quant_level1", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(myReader);
int count = dt.Rows.Count;
}
}
Why you fail!
You have created data set but you haven't load data to dataset using your DataReader. So you will get zero row count at the end.
Looks like that you want to fill your DataSet and count the rows later:
DataSet data = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(com);
da.Fill(data);
int i = data.Tables[0].Rows.Count;
Label2.Text = i.ToString();
If you just want to count the rows, you can change the query to SELECT COUNT(*) FROM quant_level1 and get the return value like this:
int i = (int) com.ExecuteScalar();
Label2.Text = i.ToString();
You should do something like this:
Select count(*) from quant_level1
Change the command syntax executescalar to retrieve a single value
CommandText = "SELECT COUNT(*) FROM region";
Int32 count = (int32) ExecuteScalar();
Hope this can enlighten you a bit
Related
I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string selstatus = "select status from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string value = Session["user"].ToString();
DataRow[] row =dt.Select(value);
sda.Fill(ds);
sda.Fill(dt);
if(row!=null){
Label13.Text = ds.Tables[0].Rows[0]["status"].ToString();
}else{
Label13.Text = "No response from mechanic";
}
cmd.ExecuteNonQuery();
con.Close();
I have been finding way to check a specific email id exist in the table. But I can't query what is the correct format to do so. I just need that if a specific email id is available then a message should be displayed.
There is no need for the DataAdapter, DataTable etc. Simply count the number of records
select count(1) from Status where c_email=#c_email
and then on the SqlCommand just use ExecuteScalar:
string selstatus = "select count(1) from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
var count = cmd.ExecuteScalar();
// if count=0 the email doesnt exist
private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.
Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);
I knew this is simple but I am not able to think. Displaying the count of a record from table and display it on textbox.
private void gMapControl1_Load_1(object sender, EventArgs e)
{
SqlConnection conDatabase = new SqlConnection(constring);
conDatabase.Open();
DataTable db = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(
"select count(site) from [ICPS].[dbo].[excel GPS postcode]",
conDatabase);
sda.Fill(db);
textBox29.Text = ;
SqlDataAdapter sda = new SqlDataAdapter(
"select count(site) from [ICPS].[dbo].[excel GPS postcode] "
+ "where Region = '1'",
conDatabase);
sda.Fill(db);
textBox30.Text = ;
}
You just need to use SqlCommand.ExecuteScalar instead of SqlDataAdapter like this:
SqlCommand com = new SqlCommand("select count(site) from [ICPS].[dbo].[excel GPS postcode]", conDatabase);
object count = com.ExecuteScalar();
if(count != null) textBox29.Text = count.ToString();
//The same for textBox30
More info on ExecuteScalar
Note that the code I posted is just for the idea of using ExecuteScalar, it depends on your code style when working with ADO.NET, you may want to use some using statement, or reuse your command, ... in your own way you like.
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
cmd.CommandText = "select count(site) from [ICPS].[dbo].[excel GPS postcode]";
Int32 count = (Int32) cmd.ExecuteScalar();
textBox29.Text = count.ToString();
}
When you expect just one value returned by your sql command, then use ExecuteScalar from the command object
string cmdText1 = "select count(site) from [ICPS].[dbo].[excel GPS postcode]";
using(SqlConnection conDatabase = new SqlConnection(constring))
using(SqlCommand cmd = new SqlCommand(cmdText, conDatabase))
{
conDatabase.Open();
int numRec = Convert.ToInt32(cmd.ExecuteScalar());
textBox29.Text = numRec.ToString();
}
MSDN says
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
However I have noticed that you try to read the record count from two different queries.
So your code could also be written in this way to avoid a roundtrip to the database
string cmdText = "select count(site) from [ICPS].[dbo].[excel GPS postcode];" +
"select count(site) from [ICPS].[dbo].[excel GPS postcode] " +
"where Region = '1'", ;
using(SqlConnection conDatabase = new SqlConnection(constring))
using(SqlCommand cmd = new SqlCommand(cmdText, conDatabase))
{
conDatabase.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
int numRec1 = Convert.ToInt32(reader[0]);
reader.NextResult();
reader.Read();
int numRec2 = Convert.ToInt32(reader[0]);
textBox29.Text = numRec1.ToString();
textBox30.Text = numRec2.ToString();
}
}
In this way I have taken advantage of the ability of SQL Server to execute two or more commands separated by a semicolon.
To fetch a value from datatable use row[columnName]
SqlDataAdapter sda = new SqlDataAdapter(
"select count(site) As siteCount from [ICPS].[dbo].[excel GPS postcode]",
conDatabase);
sda.Fill(db);
if(db !=null && db.Rows.Count > 0)
textBox29.Text =db["siteCount"].tostring();
else
textBox29.Text ="0";
However as King King suggested here why use datatable if you have to fetch just a single row and single column use ExecuteScalar method .
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. -MSDN
SqlCommand com = new SqlCommand("select count(site) from [ICPS].[dbo].[excel GPS postcode]", conDatabase);
object siteCount = com.ExecuteScalar();
if(siteCount != null) textBox29.Text = siteCount.ToString();
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.