How to use value from SQL Server in C# - c#

I got value from SQL Server using this C# code:
SqlDataReader reader = new SqlCommand("select Top 1 Client From _ClientName group by Client order by count(*) desc", sqlCon.ShardDB).ExecuteReader();
How can I use this value again to insert it into another table?

Just use name of the column begin returned from the database i.e "Client" here. If it is a string, you can use .ToString(). If it is another type, you need to convert it using System.Convert
string Value = reader["Client"].ToString();

First, for readability sake, try separating your code into separate lines, like so:
SQLReader reader;
SQLCommand SQLCmd = new SQLCommand();
SQLCmd.CommandText = "select Top 1 Client From _ClientName group by Client order by count(*) desc";
SQLCmd.Connection = sqlCon.SharedDB;
reader.Execute(SQLCmd);
If I understood your comment to Sajeetharan's previous answer, you want to know how to advance to the next result if your query returns more than one. Have you tried SQLReader.Read()?
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx

Related

Syntax error while trying to fetch data from MySql

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.

Too much connections to db using DataReader

Every time i get a value from a response from a odbcconnection by datareader, i made a connection to the database (if i have a query that return 9 fields, i have 9 connection to db), and i want to do only 1 connection and retrieve all information. it's possible with datareader ? I need to use other method of connection ?
Best Regards.
Code:
string strSql = "SELECT G.COMPANY_ID, U.USER_ID, U.GROUP_ID, U.NAME, U.DISPLAY_NAME, U.EMAIL, U.IS_CORPORATE, U.CALL_PARK, U.CALL_PICKUP, U.PCHUNTING, U.OUT_OF_OFFICE, U.DND, U.HOTLINE, U.PIN, U.FORCE_PIN_CHECKED, U.PCHUNTING_TYPE, U.DND_END_TIMESTAMP, U.DND_CONTACT, U.OUT_OF_OFFICE_TYPE, U.LANGUAGE, U.AVAILABLE_TIMESTAMP, U.LAST_DIALLED_NUMBER, U.LAST_INCOMING_CALL, U.LAST_MISSED_CALL, U.CALL_PICKUP_GROUP_ID, U.HOTLINE_NUMBER, U.PORTAL_PASSWORD, U.PROFILE, U.MAIN_NUMBER, U.DUAL_OUTGOING_CTRANSFER, U.MY_CALL_PICKUP, U.VM_RECONNECT_NOTIFY, U.SPARE_STRING1, U.INSERT_DATE, U.INSERT_USER, U.UPDATE_DATE, U.UPDATE_USER " +
"FROM {0}_TT_USER U LEFT OUTER JOIN {0}_TT_GROUP G ON U.GROUP_ID = G.GROUP_ID " +
"WHERE USER_ID = :USER_ID ";
conn = new OdbcConnection(GetIpCntrxTimestenConnString(opCode));
cmd = new OdbcCommand(
string.Format(strSql
, config.GetIpCntrxEsmViewName(opCode))
, conn);
cmd.Parameters.AddWithValue(":USER_ID", user_id);
cmd.CommandType = CommandType.Text;
conn.Open();
dataReader = cmd.ExecuteReader();
object[] meta = new object[dataReader.FieldCount];
int NumberOfColums = dataReader.GetValues(meta);
No, you need another way to query.
Instead of one query per field, SELECT all 9 at once and close the connection right away.
Another problem with this approach is that there's no layering whatsoever. I wouldn't like mingling UI and database code together. There's no abstraction your way.
Try using a StringBuilder and AppendLine your select queries. Loop through your dbReader and store in an List thats the best i can come up with. I do understand you want one call with 9 different queries but either way there is going to be overhead on your sql machine or program machine.

Problem while printing a maximum value obtained from the database

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

How can I know if such value exists in database? (ADO.NET)

For example, I have a table, and there is a column named 'Tags'. I want to know if value 'programming' exists in this column. How can I do this in ADO.NET?
I did this: OleDbCommand cmd = new OleDbCommand("SELECT * FROM table1 WHERE Tags='programming'", conn);
OleDbDataReader = cmd.ExecuteReader();
What should I do next?
use SELECT COUNT(*) and check the results.
(and use ExecuteScalar)
(assuming you know how to set the connection and use it)
SELECT TOP 1 1
FROM table1
WHERE Tags='programming'
better version, it is a good practice to use parameters instead of string concatenation, see sql injection
OleDbCommand cmd = new OleDbCommand("SELECT TOP 1 1
FROM table1 WHERE Tags=?", conn);
cmd.Parameters.Add("#p1", OleDbType.VarChar).Value = "Programming";
OleDbDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
// record exists
else
//Not exists
You should do two things:
If you are just checking the presence of a tag called Programming, you should change your query to return a COUNT instead of returning all rows.
SELECT TOP 1 Column1 FROM Table1 WHERE Tags = 'Programming'
You should check the returned set in the reader to see if there are any rows. If there are, then it means that the tag exists.

Read single value from query result

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.

Categories