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.
Related
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 )
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
So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.
I'm using the MySql Connector .net, and I need to get the insert id generated by the last query. Now, I assume the return value of MySqlHelper.ExecuteNonQuery should be the last insert id, but it just returns 1.
The code I'm using is:
int insertID = MySqlHelper.ExecuteNonQuery(Global.ConnectionString,
"INSERT INTO test SET var = #var", paramArray);
However insertID is always 1. I tried creating a MySql connection and opening/closing manually which resulted in the same behaviour
Just use LastInsertedId field
MySqlCommand dbcmd = _conn.CreateCommand();
dbcmd.CommandText = sqlCommandString;
dbcmd.ExecuteNonQuery();
long imageId = dbcmd.LastInsertedId;
1 is the no of records effected by the query here only one row is inserted so 1 returns
for getting id of the inserted row you must use scope_identity() in sqlserver and LAST_INSERT_ID() in MySql
Try to use this query to get last inserted id -
SELECT LAST_INSERT_ID();
Then, run DbCommand.ExecuteReader method to get IDataReader -
command.CommandText = "SELECT LAST_INSERT_ID()";
IDataReader reader = command.ExecuteReader();
...and get information from the reader -
if (reader != null && reader.Read())
long id = reader.GetInt64(0);
...do not forget to close the reader;-)
I had the same problem, and after some testing, I found out that the problem seem to be the connection method; you are using a connection string.
This is of course to make use of the automatic connection pool reuse, but in this case it gave me trouble.
The final solution for me is to create a new connection, execute the insert query, and then execute the last_insert_id(). On the same connection.
Without using the same connection, last_insert_id() might return anything, I don't know why, but guess it looses track of things as it can be different connections.
Example:
MySqlConnection connection = new MySqlConnection(ConnectionString);
connection.Open();
int res = MySqlHelper.ExecuteNonQuery(
connection,
"INSERT INTO games (col1,col2) VALUES (1,2);");
object ores = MySqlHelper.ExecuteScalar(
connection,
"SELECT LAST_INSERT_ID();");
if (ores != null)
{
// Odd, I got ulong here.
ulong qkwl = (ulong)ores;
int Id = (int)qkwl;
}
I hope this helps someone!
I know this is an old post, but I have been facing the same issue as Snorvarg. Using MySqlHelper, and using a connection string instead of a Connection object (to allow MySqlHelper to use connection pooling), SELECT LAST_INSERT_ID() would often give me the ID of the previous query that was executed, or other times it would return zero. I would then have to call SELECT LAST_INSERT_ID() a second time to get the correct ID.
My solution was to encapsulate everything between the query that's being executed, and the calling of SELECT LAST_INSERT_ID() in a TransactionScope. This forces MySqlHelper to stick to one connection instead of opening two separate connections.
So:
string sql = "INSERT INTO games (col1,col2) VALUES (1,2);");
string connectionString = "some connection string";
using (TransactionScope scope = new TransactionScope)
{
int rowsAffected = MySqlHelper.ExecuteNonQuery(connectionString, sql);
object id = MySqlHelper.ExecuteScalar(connectionString, "SELECT LAST_INSERT_ID();");
scope.Complete();
}
try below working solution in repository .
string query = $"INSERT INTO `users`(`lastname`, `firstname`, `email`, `createdate`, `isdeleted`) " +
$"VALUES ('{userEntity.LastName}','{userEntity.FirstName}','{userEntity.Email}','{userEntity.CreateDate}',{userEntity.IsDeleted});" +
$"SELECT LAST_INSERT_ID();";
var res= _db.ExecuteScalar(query);
return (int)(UInt64)res;
I am trying to find the MAX number from a database field,The query below returns me the maximum value if i run it in SQL Enterprise Manager but i am not able to print the value in numbwe. Please help me to print the MAX value obtained from the database.
SqlConnection MyConnection = new SqlConnection("Data Source=localhost;Initial Catalog=hcgoa;User Id=sa;Password=;");
SqlCommand MyCmd = new SqlCommand("SELECT MAX([no]) AS Expr1 FROM jmain", MyConnection);
MyConnection.Open();
SqlDataReader myReader = MyCmd.ExecuteReader();
if (myReader.Read())
{
string numbwe = myReader["no"].ToString();
Response.Write("Max no. is : " + numbwe);
}
You need to use Expr1 as the key, not no.
That's because you're doing:
SqlCommand MyCmd = new SqlCommand("SELECT MAX([no]) AS Expr1 ...
(note the AS clause) so the column is named Expr1. Hence:
string numbwe = myReader["Expr1"].ToString();
should do it.
Although, in fairness to those who come after you, Expr1 is not a very descriptive identifier. Consider the possibility of changing it to something like MaxNum (both in the select and the key, of course).
You should look at the ExecuteScalar() instead if you are going to return a single value.
MSDN: Use the ExecuteScalar method to
retrieve a single value (for example,
an aggregate value) from a database.
This requires less code than using the
ExecuteReader method, and then
performing the operations that you
need to generate the single value
using the data returned by a
SqlDataReader.
You're trying to print the value of a column that doesn't exist in the query result. Your query returns a column named Expr1, not a column named "no"
Change
string numbwe = myReader["no"].ToString();
to
string numbwe = myReader["Expr1"].ToString();
should be string numbwe = myReader["Expr1"].ToString();
as you are specifying your column name in sql statement Expr1
SELECT MAX([no]) AS Expr1