SqlDataReader showing Enumeration yielded no result - c#

am trying to read the data using SqlDataReader.
But during execution of this code reader shows "Enumeration yielded no results".
string connetionString = null;
SqlConnection cnn;
SqlCommand cmd;
string sql = null;
SqlDataReader reader;
connetionString = "Data Source=INBAGHPC00840;Initial Catalog=Testing;Persist Security Info=True;User ID=sa;Password=12345";
sql = "select * from [Category]";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
reader = cmd.ExecuteReader();
while (reader.Read()) //Here reader shows : Enumeration yielded no results
{
// MessageBox.Show(reader.GetValue(0) + " - " + reader.GetValue(1) + " - " + reader.GetValue(2));
}
reader.Close();
cmd.Dispose();
cnn.Close();
}
catch (Exception ex)
{
//MessageBox.Show("Can not open connection ! ");
}
I couldn't quite get what I am missing here. Please let me know..

Related

"ExecuteReader:Connection Property has not been initialized."

private void btnSave_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
if (rdr.Read())
{
MessageBox.Show("Company Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtStaffID.Text = "";
txtStaffID.Focus();
}
else
{
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string Query = "insert into PersonsData (StaffID, FullName, Email, Address, Picture) values('" + this.txtStaffID.Text + "','" + this.txtFullname.Text + "','" + this.txtEmail.Text + "','" + this.txtAddress.Text + "',#img)";
if (con.State != ConnectionState.Open)
con.Open();
cm = new SqlCommand(Query, con);
cm.Parameters.Add(new SqlParameter("#img", img));
int x = cm.ExecuteNonQuery();
con.Close();
MessageBox.Show(x.ToString() + "Successfully Saved!");
}
}
catch (Exception ex)
{
con.Close();
MessageBox.Show(ex.Message);
}
}
This is my code i don't understand why I'm getting this error:
ExecuteReader:Connection Property has not been initialized.
I'm making a save button where the Staffid will be checked first if already.
Before executing the command, you need to say which connection is to be used. In your case, it is:
cm.Connection = con;
Take a note that, include this line of code after opening the connection and after creating the instance of SqlCommand.
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
cm.Connection = con; //Assign connection to command
You didn't assign connection to SqlCommand used in the reader
The error message is clear enough, You have to assign the connection for the Command, either through assignement or through the constructor, That is:
cm = new SqlCommand(CheckID);
cm.Connection = con; // Should be added
SqlDataReader rdr = cm.ExecuteReader();
Or else you can use the constructor to initialize the command like this:
cm = new SqlCommand(CheckID,con);
Hope that you are aware of these things since you ware used it correctly in the else part of the given snippet
Make sure that you assign the SqlConnection to your Command-Object. You can do this via Constructor or Property:
con = new SqlConnection(//Your Connectionstring)
//assign via Constructor
cm = new SqlCommand(CheckID, con);
//or via Property
cm.Connection = con;
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
Further I would recommend you to use a using-block to make sure that the Command and Connection gets destroyed after using it.
using (var con = new SqlConnection())
{
using (var cm = new SqlCommand())
{
}
}

C# - Access Database: Why SELECT * FROM table is not working?

A simple "select * from tablename" sql query works for a table named 'mode' but not for a table named 'user'. Why?
Both tables have 2 columns. If I run the program with the "mySQL" variable as "SELECT * FROM mode" it works fine. If I put the user table instead, which means the mySQL would have been "SELECT * FROM user" then it raises an exception which says "Syntax error in FROM clause.". How can this be?
Here is the code:
static void Main(string[] args)
{
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn;
conn = new OleDbConnection(connectionstring);
try
{
conn.Open();
}
catch (Exception)
{
Console.Write("Could not connect to database");
}
String mySQL = "SELECT * FROM user";
OleDbCommand cmd = new OleDbCommand(mySQL, conn);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
}
Because USER is a reserved word in MS-Access
Change you query to encapsulate it between square brakets
SELECT * FROM [User]
albeit I suggest you to change the name of the table
Do like Steve said. And a suggestion for your code:
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn = null;
OleDbCommand cmd = null;
OleDbDataReader rdr = null;
String mySQL = "SELECT * FROM [user]";
try
{
conn = new OleDbConnection(connectionstring);
conn.Open();
cmd = new OleDbCommand(mySQL, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
conn.Close();
}
catch (Exception ex)
{
Console.Error.Write("Error founded: " + ex.Message);
}
finally
{
if (conn != null) conn.Dispose();
if (cmd != null) cmd.Dispose();
if (rdr != null) rdr.Dispose();
}

Importing from Excel to SQL Server c#

I am trying to import data from an Excel file to a table in SQL Server but it is throwing errors.
string ssqltable = "mytable";
string myexceldataquery = "select * from [Order Form$]";
try
{
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;Persist Security Info=False;data source='C:\Users\usiddiqui\Desktop\myexcel.xlsx';extended properties=" + "\'excel 12.0;hdr=yes;\';";
string ssqlconnectionstring = "server=SANJSQL-DEV;Database=db; User Id=user; Password=pass;";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.BatchSize = 100;
bulkcopy.WriteToServer(dr);
//while (dr.Read())
//{
// bulkcopy.WriteToServer(dr);
//}
dr.Close();
oledbconn.Close();
label1.Text = "File imported into sql server.";
}
catch (Exception ex)
{
//handle exception
}
the error comes on oledbconn.Open();
this is the error
Could not find installable ISAM.
You're intermixing escape syntaxes. You're using # to switch into multiline, but then you're using \ to escape. Don't escape the \'s and remove the final \ .
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=C:\Users\usiddiqui\Desktop\myexcel.xlsx;extended properties=excel 12.0;hdr=yes;";

C# and Oracle, login Form: Operation is not valid due to the current state of the object

private void bLogIn(object sender, EventArgs e)
{
string logging = "select * from CLIENT where LOGIN='" + this.t_Login.Text + "' and PASSWORD='" + this.t_Password.Text + "' ;";
OracleConnection conn = new OracleConnection("Data Source=XXX/orcl;User Id=XXX;Password=XXX;");
OracleCommand cmd = new OracleCommand();
cmd.CommandText = logging;
cmd.Connection = conn;
try
{
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
int count = 0;
OracleDataReader reader = cmd.ExecuteReader(); // At this line there is the error: Operation is not valid due to the current state of the object
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Welcome");
}
else
{
MessageBox.Show("Wrong Password");
}
conn.Dispose();
}
This is code that was working for MySQL, but after conversion to Oracle it's not working. What am I doing wrong? Where's the difference. It should be so easy as in MySQL, right?
Why "OracleDataReader reader = cmd.ExecuteReader();" causes error: "Operation is not valid due to the current state of the object" ???
You are not assingning the connection to cmd.. try code below
OracleCommand cmd = new OracleCommand();
cmd.connection = conn;
cmd.CommandText = logging;
int count = 0;
OracleDataReader reader = cmd.ExecuteReader();

Data being duplicated in a database on save

I am trying to save some data in a database using an INSERT query but it is saving double value on single click. For example I save 'Lahore', it'll save it two times:
Lahore
Lahore
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
if (dt.Read())
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}
Your code is doing exactly what you told it to.
If you call an Execute*() method twice, it will run your query twice.
It's saving twice because you are executing the query twice:
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
You are saving twice.
The executeNonQuery will return the number of rows affected so use this instead.
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
var rowsAffected = query.ExecuteNonQuery();
if (rowsAffected == 1)
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}

Categories