C# Select Transact-SQL (Table Column Property) - c#

I wanna select Table Column property using c#. I wrote this code. My query is working on the sqlserver. But i dont get max length in c#.
My Query Is Here
//TableName:Contents, ColumnName : Title
select Col_Length('Contents','Title') as columnLengthh
Result Is Here:
My C# Code Here :
string columnLength = "select Col_Length('Contents','Title') as columnLengthh";
adapter = new SqlDataAdapter(columnLength, connection);
dataSet = new DataSet();
adapter.Fill(dataSet);
DataTable dataTable2 = dataSet.Tables[0];
foreach (DataRow row in dataTable2.Rows)
{
var x = row["columnLengthh"].ToString();
}
Result (x = -1)
How i get length in c#.
Please help!

Check your query is correct
Change the connectionString to match what you have - for example:
string connectionString = #"server=localhost\mysqlserver;database=master;Trusted_Connection=True;";
and use the following code:
string queryString = "select Col_Length('Contents','Title') as columnLengthh";
string connectionString = #"your con string";
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
var result = command.ExecuteScalar();
Console.WriteLine("columnLengthh = {0}", result);
}
}
catch (Exception ex)
{
ex.ToString();
}
finally
{
connection.Close();
}

Simply use the SqlConnection, SqlCommand, SqlReader etc classes to communicate to SQL Server.
string queryString = "select Col_Length('Contents','Title') as columnLengthh";
string connectionString = "Your connection string";
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString)
using (SqlCommand command = new SqlCommand(queryString, connection)) ;
{
connection.Open();
var result = command.ExecuteScalar();
Console.WriteLine("columnLengthh = {0}", result);
}
}
finally
{
connection.Close();
}

Related

SQL command returning null for value

I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}

How to fill in and return a `DataTable` from a method with `try` and `using`?

To fill DataTable, I use the method that is presented below.
In the line adapter.Fill (table_2); i get an error:
The value can not be undefined. Parameter Name: dataTable.
Question: How to fill in and return a DataTable from a method with try and
using?
My Code
static DataTable CreateCmds_1()
{
DataTable table_2 = new DataTable();
table_2 = null;
try
{
string connectionString = #"Data Source=SRV2\SQLEXPRESS1;Initial Catalog=Prb;Integrated Security=true"; //
string queryString = "SELECT * FROM tbl_01_Groups";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
// DataTable table_3 = new DataTable();
adapter.Fill(table_2);
}
}
catch (Exception ex)
{
string s = ex.Message;
string t = ex.StackTrace;
// throw;
Console.WriteLine(s);
Clipboard.SetText(s);
Console.ReadLine();
}
return table_2;
}

DBReader supplies length of string instead of string

Currently my issue is that when I run the code it shows a datagrid with the length of the Forename Rather Than the Forename itself. Anyone got any clues, seems very silly.
List<string> NameList = new List<string>();
string connectionString = "Server = localhost; Database = TestDb; Trusted_Connection = True;";
try
{
IDbConnection dbcon;
using (dbcon = new SqlConnection(connectionString))
{
dbcon.Open();
using (IDbCommand dbcmd = dbcon.CreateCommand())
{
string sql = "Select * from people";
dbcmd.CommandText = sql;
using (IDataReader reader = dbcmd.ExecuteReader())
{
while (reader.Read())
{
string FirstName = (string) reader["ForeName"];
NameList.Add(FirstName);
}
DataGrid1.ItemsSource = NameList.ToList();
reader.Close();
dbcon.Close();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Change your List<string> to something like the following below
IList<string> NameList = new List<string>();
DataGrid1.DataSource = NameList.Select(s => new
{
Value = s
}).ToList();
something along these lines doesn't hurt to try

How to count the number of rows from sql table in c#?

How to count the number of rows from sql table in c#?
I need to extract some data from my database...
You may try like this:
select count(*) from tablename where columname = 'values'
C# code will be something like this:-
public int A()
{
string stmt = "SELECT COUNT(*) FROM dbo.tablename";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
{
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
You need to make a database connection from c# first. Then, you need to pass below query as commandText.
Select count(*) from TableName
Use ExecuteScalar/ExecuteReader to get the returned count.
Do you means likes this ?
SELECT COUNT(*)
FROM yourTable
WHERE ....
You can make global function that you can use all the time as
public static int GetTableCount(string tablename, string connStr = null)
{
string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
if (String.IsNullOrEmpty(connStr))
connStr = ConnectionString;
int count = 0;
try
{
using (SqlConnection thisConnection = new SqlConnection(connStr))
{
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
catch (Exception ex)
{
VDBLogger.LogError(ex);
return 0;
}
}
This works for me
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
For more information consult: https://learn.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN
Use this its working
string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";
connect.Open();
SqlCommand cmd = new SqlCommand(strQuery, connect);
SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
DataSet dsData = new DataSet();
OleDbDa.Fill(dsData);
connect.Close();
std.Text = dsData.Tables[0].Rows.Count.ToString();
I used this method in my own application to count the number of active users within the program. This can be easily manipulated for your own use.
con.open();
string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
SqlCommand cmd = new SqlCommand(ActiveUsers, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Close();
Users.Text = ds.Tables[0].Rows.Count.ToString();

C# MySql Storing multiple database rows in C#

I'm struggling a bit with this. I want to get the list of ids from the database where a certain value is equal to a certain value in the row. This call will likely return multiple ids. I want to store the value in the ids returned in a list or arraylist in the c# code but I am finding this troublesome. I have the code up to here:
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers + "";
connection.Open();
reader = command.ExecuteReader();
Any help would be much appreciated
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
List<string> array = new List<string>();
using (MySqlCommand cmd = new MySqlCommand("SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers, connection))
{
try
{
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
array.Add(Reader["idprojects"].ToString());
}
}
}
catch (Exception ex)
{
throw;
}
}
string[] ret= array.ToArray();

Categories

Resources