I am developing a website using ASP.NET C#. I have an SQL-Server database. I want to be able to retrieve data from the table with my data already in it.
For example, Here is my Details Table. I want to be able to do something like SELECT SteamName FROM Details WHERE SteamID = #SteamID and return the value that I get from the query to a C# object.
Here is the C# I have tried:
private void ReadSteamDetails()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT SteamID FROM Details WHERE SteamID = #SteamID";
command.Parameters.Add("#SteamID", SqlDbType.NVarChar);
command.Parameters["#SteamID"].Value = SteamID;
connection.Open();
DisplaySQLID = command.ExecuteNonQuery().ToString();
connection.Close();
}
}
}
Running this code simply returns -1
You are using ExecuteNonQuery(), that returns an int value indicating the number of rows effected by the SQL statement. It should be used with insert, update or delete, but not with select statement.
When executing a select statement, you should use either ExecuteReader() if you want to iterate the query result using a DataReader, or use a DataAdapter to fill a DataSet or a DataTable, or use ExecuteScalar() if your query should return 0 or 1 results (and that's the case here).
Also, your code can and should be shorter - for instance, you can specify the select statement and connection object directly in the SqlCommand constructor.
Here is how I would write it:
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT SteamID FROM Details WHERE SteamID = #SteamID", connection))
{
command.Parameters.Add("#SteamID", SqlDbType.NVarChar).Value = SteamID;
connection.Open();
DisplaySQLID = command.ExecuteSalar()?.ToString() ?? "";
}
}
Note that your query might not return any result so the ExecuteScalar() will return null, hence the use if the null conditional operator (?.) and the null coalescing operator (??).
For that exact query use ExecuteScalar instead of ExecuteNonQuery.
you can use the Entity Framework for that purpose. . .
with the combination of Entity Framework and link u can get your desire result set .
Entities entities = new Entities(Connection-String);
var result = entities.Details.Where(a=>a.SteamID = #SteamID )
Related
Would you please show me how to retrieve data from SQL Server to C# (Windows Forms application)?
Consider I have a textbox and I need to fill it with data from SQL Server WHERE 'emp_id = something' for example, how can I do it without a DataGridView?
Or take this another example:
SELECT sum(column) FROM table_name
How to get the value of the above command (also without a DataGridView)?
There are multiple ways to achieve this. You can use DataReader or DataSet \ DataTable. These are connected and disconnected architectures respectively. You can also use ExecuteScalar if you want to retrieve just one value.
Recommendations:
Enclose SqlConnection (and any other IDisposable object) in using block. My code uses try-catch block.
Always use parameterized queries.
Following is some example code with DataReader in case your query returns multiple rows. The code is copied from here.
//Declare the SqlDataReader
SqlDataReader rdr = null;
//Create connection
SqlConnection conn = new SqlConnection("Your connection string");
//Create command
SqlCommand cmd = new SqlCommand("Your sql statement", conn);
try
{
//Open the connection
conn.Open();
// 1. get an instance of the SqlDataReader
rdr = cmd.ExecuteReader();
while(rdr.Read())
{
// get the results of each column
string field1 = (string)rdr["YourField1"];
string field2 = (string)rdr["YourField2"];
}
}
finally
{
// 3. close the reader
if(rdr != null)
{
rdr.Close();
}
// close the connection
if(conn != null)
{
conn.Close();
}
}
In case your query returns single value, you can continue with above code except SqlDataReader. Use int count = cmd.ExecuteScalar();. Please note that ExecuteScalar may return null; so you should take additional precautions.
Filling a Textbox:
using (var sqlConnection = new SqlConnection("your_connectionstring"))
{
sqlConnection.Open();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = "select sum(field) from your_table";
object result = sqlCommand.ExecuteScalar();
textBox1.Text = result == null ? "0" : result.ToString();
}
sqlConnection.Close();
}
for reading more than one row you can take a look at SqlCommand.ExecuteReader()
You need to use direct database access such as in the System.Data.SqlClient Namespace which is documented here System.Data.SqlClient Namespace.
Basically, look up creating a SQLConnection and SQLCommand and using them to retrieve the data.
I am somwhat new to SQL, so I am not sure I am going about this the right way.
I am trying to fetch data from my SQL Server database where I want to find out if checkedin is 1/0, but it needs to search on a specific user and sort after the newest date as well.
What I am trying to do is something like this:
string connectionString = ".....";
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand checkForInOrOut = new SqlCommand("SELECT CHECKEDIN from timereg ORDER BY TIME DESC LIMIT 1 WHERE UNILOGIN = '" + publiclasses.unilogin + "'", cnn);
So my question, am I doing this right? And how do I fetch the data collected, if everything was handled correctly it should return 1 or 0. Should I use some sort of SqlDataReader? I am doing this in C#/WPF
Thanks
using (SqlDataReader myReader = checkForInOrOut.ExecuteReader())
{
while (myReader.Read())
{
string value = myReader["COLUMN NAME"].ToString();
}
}
This is how you would read data from SQL, but i recommend you looking into Parameters.AddWithValue
There are some errors in your query. First WHERE goes before ORDER BY and LIMIT is an MySql keyword while you are using the Sql Server classes. So you should use TOP value instead.
int checkedIn = 0;
string cmdText = #"SELECT TOP 1 CHECKEDIN from timereg
WHERE UNILOGIN = #unilogin
ORDER BY TIME DESC";
string connectionString = ".....";
using(SqlConnection cnn = new SqlConnection(connectionString))
using(SqlCommand checkForInOrOut = new SqlCommand(cmdText, cnn))
{
cnn.Open();
checkForInOrOut.Parameters.Add("#unilogin", SqlDbType.NVarChar).Value = publiclasses.unilogin;
// You return just one row and one column,
// so the best method to use is ExecuteScalar
object result = checkForInOrOut.ExecuteScalar();
// ExecuteScalar returns null if there is no match for your where condition
if(result != null)
{
MessageBox.Show("Login OK");
// Now convert the result variable to the exact datatype
// expected for checkedin, here I suppose you want an integer
checkedIN = Convert.ToInt32(result);
.....
}
else
MessageBox.Show("Login Failed");
}
Note how I have replaced your string concatenation with a proper use of parameters to avoid parsing problems and sql injection hacks. Finally every disposable object (connection in particular) should go inside a using block
i'm fetching values from a table with datareader like this:
string query = #"SELECT XMLConfig, Enable FROM TableCfg";
using (SqlConnection cnction = new SqlConnection(cnnstr))
{
cnction.Open();
using (SqlCommand sqlCmd = new SqlCommand(query, cnction))
{
SqlDataReader dtRead = sqlCmd.ExecuteReader();
while (dtRead.Read())
{
xmlConf = dtRead.GetString(0);
enabl = dtRead.GetString(1);
}
dtRead.Close();
}
}
The Enable field is a boolean(True/False). Is there a way to fetch only the rows, where field enable="True"?
I tried using LINQ, but i'm new to this and i must be doing something wrong.
using (SqlCommand sqlCmd = new SqlCommand(query, cnction))
{
SqlDataReader dtRead = sqlCmd.ExecuteReader();
var ob =(from IDataRecord r in sqlCmd.ExecuteReader()
where r.GetString(3).ToString() == "True"
select "Enable");
}
Help me please.
Best Regards.
You should really do as much filtering as possible at the database side rather than client-side:
string query = "SELECT XMLConfig FROM TableCfg WHERE Enable = True";
Notice how now you don't even need to fetch Enable, as you already know it will be True for all the matching rows.
You should also consider using LINQ to SQL or Entity Framework rather than the rather low-level stack you're currently using. It's not always appropriate, but it does make things cleaner where it's suitable.
Problem statement.
Basically I get 3 - 50 parameters that come back from a web service as a NVP array I then need to loop over them create the SQL command parameters for each and call the stored procedure. Is there a more efficient way to handle it than the approach below?
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cm = connection.CreateCommand())
{
cm.CommandText = "MySproc";
cm.CommandType = CommandType.StoredProcedure;
foreach (var field in row)
{
cm.Parameters.AddWithValue("#" + field.Key.ToString(), field.Value.ToString());
}
cm.ExecuteNonQuery();
}
}
I personally use the ISNULL or COALESCE in the WHERE clause of the stored procedure. Unless your looking to do it inside your c#...
http://blogs.x2line.com/al/archive/2004/03/01/189.aspx
I am trying to return the result that I found in my query to the ASP.net table. How do I do that? I already have the query, I am just having trouble getting the count result back.
string configMan.ConnString["connect"].ToString();
iDB2Conn temp = new iDB2Conn
string query = "select Count(*) as total from test";
...
this is where I am having trouble.
This is where the SqlCommand object comes in handy.
int result = 0;
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand sql = new SqlCommand("SELECT COUNT(*) FROM test", conn);
result = (int)sql.ExecuteScalar();
}
In ADO.Net, the simplest way is to use the ExecuteScalar() method on your command which returns a single result. You don't explicitly list what database or connection method you are using, but I would expect that most database access methods have something equivalent to ExecuteScalar().
Try using the ExecuteScalar method on your command. You should be able to use the generic one or cast the result to an int/long.