con.Open();
cmd = new SqlCommand("USE PRODUCTS SELECT BOUGHT FROM " +
DropDownList1.SelectedItem.Text +
" WHERE ID = #ID", con);
cmd.Parameters.Add("ID", SqlDbType.Int).Value = DropDownList2.SelectedIndex;
int i = cmd.ExecuteReader().GetInt32(0);
con.Close();
I can't read integer values with reader like this. I get runtime error System.InvalidOperationException. What is wrong with my code ? if you can't find the mistake, can you explain how can i read integer values with reader ? By the way this part of code gives the error:
int i = cmd.ExecuteReader().GetInt32(0);
Try this:
int x=0;
using (
SqlConnection connection = new SqlConnection(strCon))
{
SqlCommand command = new SqlCommand(sql_string, connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
x = reader.GetInt32(0);
}
}
reader.Close();
}
You need to initialise a reader and then read it
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read()) // or just rdr.Read() if you know only one row is returned
{
int i = rdr.GetInt32(0);
What I have done to make things a lot easier on my end, since I mainly use SQL all over the place, is make some extensions.
eg
public static Int32 GetInt32(this SqlDataReader rdr, string column)
{
return Convert.ToInt32(rdr[column]);
}
Related
I have written the following code to query stuff from a SQL Server database. The query in the first reader works, but not in the second. I just can't seem to figure out why as the approach is exactly the same in both readers. Any help is much appreciated.
The parameters for the commands are given in the function above which isn't in the code btw.
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "...";
conn.Open();
SqlCommand command = new SqlCommand("SELECT stuff FROM table WHERE Belegnummer= #n and Belegjahr=#j", conn);
command.Parameters.Add(new SqlParameter("n", nr));
command.Parameters.Add(new SqlParameter("j", jahr));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
r = reader.GetInt32(0);
}
}
command.Dispose();
SqlCommand command2 = new SqlCommand("SELECT stuff1, stuff2, stuff3 FROM sameTable WHERE BelID = #rnr", conn);
command2.Parameters.Add(new SqlParameter("rnr", r));
using (SqlDataReader reader2 = command2.ExecuteReader())
{
while (reader2.Read())
{
// variables are defined somewhere above
b = reader2.GetInt32(0);
j = reader2.GetInt32(1);
m = reader2.GetInt32(2);
}
}
}
Please post the error messages as well.
You may run into trouble with DbNull values. Check for DbNull before you parse the values with:
SqlReader.IsDBNull(column)
Or load the Data into a DataTable:
DataTable dt = new DataTable();
using (SqlDataReader reader = cmd1.ExecuteReader())
{
dt.Load(reader);
}
I'm working on application which needs to connect to another database to get some data,
and to do that, I decided to use SqlConnection, reader etc..
And I need to execute few queries, for example first I need to get CARD ID for some user, after that I need to get some data by that CARD ID..
Here is my code:
#region Connection to another Database
SqlConnection sqlConnection1 = new SqlConnection("Data Source=ComputerOne; Initial Catalog=TestDatabase;Integrated Security=False; User ID=test; Password=test123;");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * From Users Where CardID=" + "'" + user.CardID + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
string cardID = "";
string quantity="";
while (reader.Read())
{
cardID = reader["CardID"].ToString();
}
//HOW COULD I WRITE ANOTHER QUERY NOW, FOR EXAMPLE, OK I GOT CARDID NOW GIVE ME SOME OTHER THINGS FROM THAT DATABASE BY THAT cardID
//here I tried to change CommandText and to keep working with reader.. but its not working like this because its throwing me exception mention in question title.
cmd.CommandText = "Select T1.CardID, T2.Title, Sum(T1.Quantity) as Quantity From CardTransactions as T1 JOIN Adds as T2 ON T1.AddsID = T2.AddsID Where T1.CardID =" + cardID + "AND T1.Type = 1 Group By T1.CardID, T2.Title";
reader = cmd.ExecuteReader();
while (reader.Read())
{
quantity = reader["Quantity"].ToString();
}
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
#endregion
So guys how could I execute few queries statemens using this example.
Thanks a lot!
Cheers
Your problem is that you are not disposing the objects you are using. For that purpose is better to always use using structure, since it will guarantee you that everithing is gonna be disposed. Try the code below:
SqlConnection sqlConnection1 = new SqlConnection("Data Source=ComputerOne; Initial Catalog=TestDatabase;Integrated Security=False; User ID=test; Password=test123;");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
string cardID = "";
string quantity="";
using(sqlConnection1 = new SqlConnection("Data Source=ComputerOne; Initial Catalog=TestDatabase;Integrated Security=False; User ID=test; Password=test123;"))
{
sqlConnection1.Open();
using(cmd = new SqlCommand())
{
cmd.CommandText = "Select * From Users Where CardID=" + "'" + user.CardID + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
cardID = reader["CardID"].ToString();
}
} //reader gets disposed right here
} //cmd gets disposed right here
using(cmd = new SqlCommand())
{
cmd.CommandText = "Select T1.CardID, T2.Title, Sum(T1.Quantity) as Quantity From CardTransactions as T1 JOIN Adds as T2 ON T1.AddsID = T2.AddsID Where T1.CardID =" + cardID + "AND T1.Type = 1 Group By T1.CardID, T2.Title";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
quantity = reader["Quantity"].ToString();
}
} //reader gets disposed right here
} //cmd gets disposed right here
sqlConnection1.Close();
} //sqlConnection1 gets disposed right here
The reader you opened is still active and open. And you can have just one active reader at a time. You should wrap all Sql... instances in a using to ensure they get closed properly.
using (SqlConnection connection = new SqlConnection(...))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// the code using reader
}
}
well ... you receive the error because the used reader for the first call was not closed. You should always call the Close method when you have finished using the DataReader object insuring that the connection used by the reader is returned to the connection pool (the connection is in use exclusively by that DataReader). Partial code:
reader = cmd.ExecuteReader();
try
{
while(myReader.Read())
{
while (reader.Read())
{
cardID = reader["CardID"].ToString();
}
}
finally
{
myReader.Close();
}
...
reader = cmd.ExecuteReader();
try
{
while(myReader.Read())
{
reader = cmd.ExecuteReader();
while (reader.Read())
{
quantity = reader["Quantity"].ToString();
}
}
}
finally
{
myReader.Close();
myConnection.Close();
}
Also... as a clean code rule, separate your calls in different methods (SOLID principles)
I am a newbie in ASP.NET, having trouble in how to call an inline User Defined Function in my ASP.NET web application.
Here, I have passed two arguments in my function - one is available leave(lv) and another one is duration (dr). I am simply subtracting dr from lv and returning the value. But I am having problem in calling the function.
I have tried "SELECT dbo.emp_leave_sub(lv,dr) as remaining" instead of the query "SELECT dbo.emp_leave_sub(lv,dr) FROM Employee1 where Employee1.emp_id='" + emp_id + "'" but it didn't work. I can not understand what I am doing wrong.
Looking forward to your kind reply. Any help will be highly appreciated.
Below is my function :
ALTER FUNCTION dbo.emp_leave_sub(#available int, #duration int)
RETURNS int
AS
-- Returns the availabe leave after deduction for the employee.
BEGIN
DECLARE #ret int;
SELECT #ret = #available - #duration;
RETURN #ret;
END;
And this is from where I am calling my function :
try
{
SqlDataReader rdr;
SqlConnection conn = new SqlConnection (ConfigurationManager.
ConnectionStrings["PMSConnectionString"].ConnectionString);
conn.Open();
string sub_leave = "SELECT dbo.emp_leave_sub(lv,dr) FROM ` ` Employee1 where Employee1.emp_id='" + emp_id + "'";
SqlCommand com2 = new SqlCommand(sub_leave, conn);
com2.CommandType = CommandType.Text;
using (conn)
{
//read data from the table to our data reader
rdr = com2.ExecuteReader();
//loop through each row we have read
while (rdr.Read())
{
remaining = rdr.GetInt32(0);
}
rdr.Close();
}
Try to do this:
SqlDataReader rdr;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PMSConnectionString"].ConnectionString))
{
conn.Open();
string sub_leave = "SELECT dbo.emp_leave_sub(#available,#duration) FROM Employee1 where Employee1.emp_id=#empid";
SqlCommand com2 = new SqlCommand(sub_leave, conn);
com2.Parameters.AddWithValue("#available", your value);
com2.Parameters.AddWithValue("#duration", your value);
com2.Parameters.AddWithValue("#empid", emp_id);
com2.CommandType = CommandType.Text;
//read data from the table to our data reader
rdr = com2.ExecuteReader();
//loop through each row we have read
while (rdr.Read())
{
remaining = rdr.GetInt32(0);
}
}
rdr.Close();
Working with C# and MySQL here (Visual Studio 12 and MySQL workbench 6.1).
I'm trying to get the entire table into a list.
This is what I have so far:
List<Object> arrList = new List<Object>();
string str = #"server=localhost;database=test;userid=root;password=asd;";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
arrList.Add(reader["* "]);
}
When I pass SELECT * FROM emp; for query and try to get a toString of arrList, I get an indexOutOfBounds exception. (My table emp has 1 record in it.)
Thanks!
Edit: I'm trying to get the entire table (sequentially) into a list. Is this the right approach?
Edit 2: What if we don't know the number of columns in the table?
Change to:
while (reader.Read())
{
arrList.Add(reader["myColumnTitle"].ToString());
}
cause "* " isn't a valis columnname. alternative you can use an index
arrList.Add(reader[0].ToString());
for each Column:
List arrList = new List();
string str = #"server=localhost;database=test;userid=root;password=asd;";
string query = "SELECT * FROM emp";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
var value = reader[i];
arrList.Add(Convert.ToString(value))
}
}
reader.Read() read your results row by row. That means inside this while statement, you need to read all columns of your query.
When you write "* ", your reader looks for a column named * which you don't have. MySqlDataReader can't understand to read all columns when you write * as you can in an sql query.
This should work.
while (reader.Read())
{
arrList.Add((string)reader[0]);
arrList.Add((string)reader[1]);
}
If you really don't know how many fields that your MySqlDataReader has, you can use SqlDataReader.FieldCount property.
Gets the number of columns in the current row.
So you code can be like;
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
Also use using statement to dispose your database connections and objects like;
using(MySqlConnection con = new MySqlConnection(str))
using(MySqlCommand cmd = con.CreateCommand())
{
...
...
using(MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
}
}
I am fetching records of users and binding it to gridview. I want to show the number of results returned like "15 results found". I used RecordsAffected but I think it wont work with select statement. Any alternate way?
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name, city, number where age between " + from.Text + "AND " + to.Text;
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
reader.Close();
usersgrid.DataSource = cmd.ExecuteReader();
usersgrid.DataBind();
con.Close();
}
else
{
result.Visible = true;
}
}
}
Now I want to show number of rows returned on a label.
int affectedRows = cmd.ExecuteNonQuery();
that would work for you insted of cmd.ExecuteReader();
another alternative will be to get rowcount of the usersGrid control
int Count = usersGrid.Rows.Count-((usersGrid.PageCount-1) * usersGrid.PageSize);