Displaying Selected values(Sql query) using c# and html - c#

I want to display the data that is selected in the SQL query , I tried to use ExecuteScalar() but it only work with 1 value , here is my c# code :
SqlConnection conn = new SqlConnection("Data Source=MAX-PC\\SQLEXPRESS;Initial Catalog=newSchool;Integrated Security=True");
SqlCommand cmd = new SqlCommand("view_profile", conn);
cmd.CommandText = "exec view_profile #posted_id";
cmd.Parameters.AddWithValue("#posted_id", WebForm1.x);
conn.Open();
cmd.ExecuteNonQuery;
conn.Close();
and that's the proc :
CREATE PROC view_profile
#posted_in INTEGER
AS
BEGIN
SELECT P.poster , P.post_description
FROM Posts P
WHERE P.posted_in = #posted_in
END

you are a little confused:
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.
ExecuteNonQuery(): Executes a Transact-SQL statement against the connection and returns the number of rows affected, it is intended for UPDATE, INSERT and DELETE queries
What you need is ExecuteReader()
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}

Related

My select command doesn't work

I am working with Visual Studio 2010 and I added a new Item as report.mdf to my project as database; I created a table Table1 and I have added one record manually to the Table1; but when I try to select the data I can not do it and get this error:
invalid attempt to read when no data is present
This is my code:
SqlCommand objcomand = new SqlCommand();
SqlConnection con = new SqlConnection();
con.ConnectionString=#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\EHSAN\My Documents\Visual Studio 2010\Projects\report\report\App_Data\report.mdf;Integrated Security=True;User Instance=True";
objcomand.Connection = con;
objcomand.CommandText = "select * from Table1";
con.Open();
SqlDataReader reader1 = objcomand.ExecuteReader();
string i = reader1.GetValue(1).ToString();
con.Close();
You have to advance the DataReader to the next block of data with SqlDataReader.Read:
string i = null;
// use using for everything that implements IDisposable like a Connection or a DataReader
using(var reader1 = objcomand.ExecuteReader())
{
// a loop since your query can return multiple records
while(reader1.Read())
{
// if the field actually is the first you have to use GetString(0)
i = reader1.GetString(1);
}
}

How do I store a SQL stored procedure result that returns a row or a column value into an ASP.NET C# variable?

I have a SQL stored procedure that returns a column value (SQL data type: nchar(1)). The stored procedure runs and comes back with desired value when a parameter is passed. Based on this returned value, I want to divert the program flow. For this I need to read the value returned in an ASP.NET C# variable, but I am not sure how can I do this.
create procedure sproc_Type
#name as nchar(10)
AS
SELECT Type FROM Table WHERE Name = #name
I want to read Type value in .cs file and want to save it for later use.
SqlConnection conn = null;
SqlDataReader rdr = null;
conn = new
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand(
"Stored_PROCEDURE_NAME", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#PARAMETER_NAME", PARAMETER_VALUE));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
var result = rdr["COLUMN_NAME"].ToString();
}
string connectionString = "(your connection string here)";
string commandText = "usp_YourStoredProc";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
// your code to fetch here.
}
conn.Close();
}

Get int value from command in c#

string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
cmd.ExecuteScalar(); //this statement return 0
but I want to get the id of user?
how can I get it?
You need the SqlDataReader.
SqlDataReader Provides a way of reading a forward-only stream of rows from a SQL Server database.
Sample
string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) {
rd.Read(); // read first row
var userId = rd.GetInt32(0);
}
More Information
MSDN - SqlDataReader Class
Simply cast the returned value:
int userId = (Int32)cmd.ExecuteScalar();
But be aware that ExecuteScalar will return null if your query returns an empty result set, and in that case the above code snippet will throw an InvalidCastException.
try with select TOP 1 and ExecuteScalar
string sql = "Select TOP 1 UserId From User where UserName='Gheorghe'";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
var result = (Int32)cmd.ExecuteScalar();
}
}

2 rows inserted instead of 1 when using ##IDENTITY / scope_identity()

using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID); SELECT CAST(scope_identity() AS int)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
int lastID = (int)command.ExecuteScalar();
}
Without the
SELECT CAST(scope_identity() AS int)
One row is inserted. But since I need the ID from the created row im using scope_identity. However, when I use this, 2 rows are created instead of one.
Did I miss something?
Thanks
The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();
If you try to use only the executeScalar i think you have the result's you want....
Try and hope this helps...
If you want you can use Parameter to retrieve the Identity, like they do in this Article
If you would use gbn or my answer from your first question, the problem shouldn't occur.
Try doing
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID);";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
query = "SELECT CAST(scope_identity() AS int)";
command = new SqlCommand(query, connection);
int lastID = (int)command.ExecuteScalar();
}

Simple SQL select in C#?

On my current project, to get a single value (select column from table where id=val), the previous programmer goes through using a datarow, datatable and an sqldatadapter (and of course sqlconnection) just to get that one value.
Is there an easier way to make a simple select query? In php, I can just use mysql_query and then mysql_result and I'm done.
It would be nice if I could just do:
SqlConnection conSql = new SqlConnection(ConnStr);
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql);
conSql.Close();
return obj[0];
Thanks for any tips.
You can skip the DataReader and the DataAdapter and just call ExecuteScalar() on the sql command.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You are probably looking for SqlCommand and SqlDataReader
Dictionary<int, string> users = new Dictionary<int, string>();
using(SqlConnection connection = new SqlConnection("Your connection string"))
{
string query = "SELECT UserId, UserName FROM Users";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
users.Add(reader.GetInt32(0), reader.GetString(1));
}
connection.Close();
}
Actually, there is a method SqlCommand.ExecuteScalar() that will simply return the first field from the first row of the returned results. Just for you.
.NET Framework Class Library
SqlCommand..::.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.
You can do something very similar:
using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(sql_string, conn))
{
conn.Open();
return cmd.ExecuteScalar();
}
you can use SqlCommands executeScalar function. Please look at the following link
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

Categories

Resources