DBReader supplies length of string instead of string - c#

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

Related

SQL Server not executing SqlExecuteReader

I'm stumped, I have been trying to execute this and nothing happens. I know that the code reaches this point but it doesn't matter if I put gibberish in the SQL statement, it doesn't throw an error.
protected string checkLaptopStatus(String cardID)
{
String ConnString = GetConnectSQLServer();
String currentStatus = "";
int i = 0;
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "SELECT laptopStatus FROM tblDevices WHERE cardID = " + cardID + "'";
m_dbConnection.Open();
// CODE REACHES THIS POINT BUT NEVER PASSES THIS ?
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
currentStatus = Convert.ToString(dr["laptopStatus"]);
i++;
}
}
}
}
return currentStatus;
}
Changed the code as advised and used the exception error message to find out what went wrong. thanks Joel for being kind and helping.
protected void SQLReaderLaptops(string cardID)
{
String ConnString = GetConnectSQLServer();
int i = 0;
String todaysDate = DateTime.Now.ToString("yyyy'-'MM'-'dd");
String laptopID = "";
try {
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "Select laptopID From tblDevices WHERE cardID= #cardID";
m_dbConnection.Open();
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#cardID", cardID);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
laptopID = Convert.ToString(dr["laptopID"]);
i++;
}
}
}
}
}
catch(Exception ex)
{
//CAUGHT THE ISSUE HERE AND FOUND IT WAS A BAD COLUMN NAME
}

How can I Store SQL Server Query Results into a List of String?

I want to store what's returned from a database query into a list of string. I've got this code:
List<String> slDistinctUncommonWords = new List<string>();
. . .
slDistinctUncommonWords = GetDistinctWordsFromDB();
. . .
private List<String> GetDistinctWordsFromDB()
{
List<String> slDistinctWords = new List<string>();
try
{
string sQuery = "SELECT DISTINCT UncommonWord " +
"FROM WORDSTATS " +
"ORDER BY UncommonWord";
SqlConnection sqlConnection = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(sQuery, sqlConnection);
sqlConnection.Open();
slDistinctWords = (List<String>)cmd.ExecuteScalar();
sqlConnection.Close();
return slDistinctWords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
The "slDistinctUncommonWords = GetDistinctWordsFromDB();" line fails, though, with "Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List'1[System.String]'".
You could use ExecuteReader instead of ExecuteScalar, like the following code:
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
slDistinctWords.Add(reader["UncommonWord"].ToString());
}
}
I hope you find this helpful.
Put into a datatable
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
List<string> slDistinctWords = dt.AsEnumerable().Select(x => x.Field<string>(0)).Distinct().ToList();
A SqlDataReader can be treated as a collection of IDataRecord objects. So
var col = new List<String>();
using (var rdr = cmd.ExecuteReader())
{
col = rdr.Cast<IDataRecord>().Select(r => r.GetString(0)).ToList();
}
If you are using Microsoft SQL Server, try to replace your SQL query statement with this:
string sQuery = "SELECT DISTINCT CAST(UncommonWord AS VARCHAR(32)) + ',' " +
"FROM WORDSTATS " +
"ORDER BY UncommonWord FOR XML PATH('')";
This works:
private List<String> GetDistinctWordsFromDB()
{
List<String> slDistinctWords = new List<string>();
try
{
string sQuery = "SELECT DISTINCT UncommonWord " +
"FROM WORDSTATS " +
"ORDER BY UncommonWord";
SqlConnection sqlConnection = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(sQuery, sqlConnection);
SqlDataReader reader;
sqlConnection.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
slDistinctWords.Add(reader.GetString(0));
}
reader.Close();
sqlConnection.Close();
return slDistinctWords;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}

Is there any proper way to retrieve data from OLEDB connection searched by some specific string value?

I wanted to retrieve a Category from SQL Server using this query. I have data in the database and this query worked well in SQL Server. But when I use it with oledb command, it does not return any data from the server. What's the problem?
public Category GetCategoryByCategoryName(string categoryName)
{
Category _category = null;
using (OleDbConnection con = new OleDbConnection(_connectionString))
{
string sql = "select * from Categories where CategoryName=?";
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#cName", categoryName);
try
{
con.Open();
OleDbDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
_category.Id = Convert.ToInt32(rdr["Id"]);
_category.CategoryName = rdr["CategoryName"].ToString();
}
rdr.Close();
}
}
catch (Exception ex)
{
_category = null;
}
}
return _category;
}
I don't know about "proper" but a "good" way might be to install Dapper and reduce your code to:
public Category GetCategoryByCategoryName(string categoryName)
{
using (OleDbConnection con = new OleDbConnection(_connectionString))
{
return con.QueryFirstOrDefault<Category>(
"select * from Categories where CategoryName=?cn?",
new { cn = categoryName }
);
}
}
References:
Passing query parameters in Dapper using OleDb
It should:
Category _category = new Category();
instead of:
Category _category = null;

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;
}
}

C# Select Transact-SQL (Table Column Property)

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();
}

Categories

Resources